-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpSession.psm1
More file actions
347 lines (310 loc) · 14.1 KB
/
McpSession.psm1
File metadata and controls
347 lines (310 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<#
.SYNOPSIS
MCP Session Log PowerShell module — cmdlets for the /mcpserver/sessionlog API.
.DESCRIPTION
Provides cmdlets to create, update, query, and manage session logs on an MCP Context Server.
Automatically reads connection details from the AGENTS-README-FIRST.yaml marker file.
.NOTES
Usage: Import-Module ./McpSession.psm1
Initialize-McpSession # reads marker, sets connection
$s = New-McpSessionLog -Title "My session" # creates session
Add-McpSessionEntry -Session $s -QueryTitle "Fix bug" -QueryText "Fix the auth bug" -Status in_progress
Send-McpDialog -Session $s -RequestId req-001 -Content "Analyzing the issue..." -Category reasoning
Update-McpSessionLog -Session $s # pushes to server
#>
# ─── Module state ────────────────────────────────────────────────────────────
$script:McpBaseUrl = $null
$script:McpApiKey = $null
$script:McpWorkspacePath = $null
$script:McpHeaders = @{}
# ─── Connection ──────────────────────────────────────────────────────────────
function Initialize-McpSession {
<#
.SYNOPSIS Read the AGENTS-README-FIRST.yaml marker and configure the module connection.
.PARAMETER MarkerPath Path to the marker file. Defaults to searching upward from the current directory.
.PARAMETER BaseUrl Override the base URL instead of reading from the marker.
.PARAMETER ApiKey Override the API key instead of reading from the marker.
#>
[CmdletBinding()]
param(
[string]$MarkerPath,
[string]$BaseUrl,
[string]$ApiKey
)
if ($BaseUrl -and $ApiKey) {
$script:McpBaseUrl = $BaseUrl.TrimEnd('/')
$script:McpApiKey = $ApiKey
} else {
if (-not $MarkerPath) {
$dir = (Get-Location).Path
while ($dir) {
$candidate = Join-Path $dir "AGENTS-README-FIRST.yaml"
if (Test-Path $candidate) { $MarkerPath = $candidate; break }
$parent = Split-Path $dir -Parent
if (-not $parent -or $parent -eq $dir) { break }
$dir = $parent
}
}
if (-not $MarkerPath -or -not (Test-Path $MarkerPath)) {
throw "AGENTS-README-FIRST.yaml not found. Provide -MarkerPath, or run from within a workspace."
}
$content = Get-Content $MarkerPath -Raw
$script:McpBaseUrl = ([regex]::Match($content, 'baseUrl:\s*(\S+)')).Groups[1].Value
$script:McpApiKey = ([regex]::Match($content, 'apiKey:\s*(\S+)')).Groups[1].Value
$script:McpWorkspacePath = ([regex]::Match($content, 'workspacePath:\s*(.+)')).Groups[1].Value.Trim()
}
$script:McpHeaders = @{
"X-Api-Key" = $script:McpApiKey
"Content-Type" = "application/json"
"X-Workspace-Path" = $script:McpWorkspacePath
}
# Verify connectivity
try {
$health = Invoke-RestMethod -Uri "$($script:McpBaseUrl)/health" -TimeoutSec 5
Write-Host "Connected to MCP server at $($script:McpBaseUrl) — status: $($health.status)" -ForegroundColor Green
} catch {
Write-Warning "MCP server at $($script:McpBaseUrl) is not responding: $_"
}
}
# ─── Session object ──────────────────────────────────────────────────────────
function New-McpSessionLog {
<#
.SYNOPSIS Create a new session log object and POST it to the server.
.PARAMETER SourceType Agent identifier (e.g. "Copilot", "Cline", "Cursor").
.PARAMETER SessionId Stable session ID prefixed with agent name. Auto-generated if omitted.
.PARAMETER Title Brief session summary.
.PARAMETER Model AI model name (e.g. "claude-sonnet-4-20250514").
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$SourceType,
[string]$SessionId,
[Parameter(Mandatory)][string]$Title,
[Parameter(Mandatory)][string]$Model
)
Assert-Initialized
if (-not $SessionId) {
$ts = (Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssZ')
$slug = ($Title -replace '[^a-zA-Z0-9]+', '-' -replace '^-|-$', '').ToLower()
if ($slug.Length -gt 30) { $slug = $slug.Substring(0, 30) -replace '-$', '' }
if (-not $slug) { $slug = 'session' }
$SessionId = "$SourceType-$ts-$slug"
}
$now = (Get-Date).ToUniversalTime().ToString("o")
$session = [PSCustomObject]@{
sourceType = $SourceType
sessionId = $SessionId
title = $Title
model = $Model
started = $now
lastUpdated = $now
status = "in_progress"
entries = [System.Collections.Generic.List[object]]::new()
}
Push-SessionLog $session
return $session
}
function Update-McpSessionLog {
<#
.SYNOPSIS Push the current session log state to the server.
.PARAMETER Session The session object returned by New-McpSessionLog.
.PARAMETER Status Optionally change status to "completed".
.PARAMETER Title Optionally update the title.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][PSCustomObject]$Session,
[ValidateSet("in_progress","completed")][string]$Status,
[string]$Title
)
Assert-Initialized
$Session.lastUpdated = (Get-Date).ToUniversalTime().ToString("o")
if ($Status) { $Session.status = $Status }
if ($Title) { $Session.title = $Title }
Push-SessionLog $Session
}
function Get-McpSessionLog {
<#
.SYNOPSIS Query recent session logs from the server.
.PARAMETER Limit Number of sessions to return (default 5).
.PARAMETER Offset Pagination offset.
#>
[CmdletBinding()]
param(
[int]$Limit = 5,
[int]$Offset = 0
)
Assert-Initialized
$uri = "$($script:McpBaseUrl)/mcpserver/sessionlog?limit=$Limit&offset=$Offset"
return Invoke-RestMethod -Uri $uri -Headers $script:McpHeaders
}
# ─── Entries ─────────────────────────────────────────────────────────────────
function Add-McpSessionEntry {
<#
.SYNOPSIS Add a request entry to the session and push to server.
.PARAMETER Session The session object.
.PARAMETER RequestId Unique ID for this request. Auto-generated if omitted.
.PARAMETER QueryTitle Short summary of the query.
.PARAMETER QueryText Full user query or task description.
.PARAMETER Interpretation Your understanding of what was asked.
.PARAMETER Response Your response text.
.PARAMETER Status "in_progress" or "completed".
.PARAMETER Model Model used for this entry. Defaults to session model.
.PARAMETER Tags Array of tags (e.g. "refactor", "bugfix").
.PARAMETER ContextList Array of files or resources referenced.
.PARAMETER Push If set, immediately push to server. Default: true.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][PSCustomObject]$Session,
[string]$RequestId,
[Parameter(Mandatory)][string]$QueryTitle,
[Parameter(Mandatory)][string]$QueryText,
[string]$Interpretation = "",
[string]$Response = "",
[ValidateSet("in_progress","completed")][string]$Status = "in_progress",
[string]$Model,
[string[]]$Tags = @(),
[string[]]$ContextList = @(),
[switch]$NoPush
)
if (-not $RequestId) {
$ts = (Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssZ')
$ord = '{0:D3}' -f ($Session.entries.Count + 1)
$RequestId = "req-$ts-$ord"
}
if (-not $Model) { $Model = $Session.model }
$entry = [PSCustomObject]@{
requestId = $RequestId
timestamp = (Get-Date).ToUniversalTime().ToString("o")
queryText = $QueryText
queryTitle = $QueryTitle
response = $Response
interpretation = $Interpretation
status = $Status
model = $Model
tags = $Tags
contextList = $ContextList
designDecisions = [System.Collections.Generic.List[string]]::new()
requirementsDiscovered = [System.Collections.Generic.List[string]]::new()
filesModified = [System.Collections.Generic.List[string]]::new()
blockers = [System.Collections.Generic.List[string]]::new()
actions = [System.Collections.Generic.List[object]]::new()
processingDialog = [System.Collections.Generic.List[object]]::new()
}
$Session.entries.Add($entry)
if (-not $NoPush) {
Update-McpSessionLog -Session $Session
}
return $entry
}
function Set-McpSessionEntry {
<#
.SYNOPSIS Update fields on an existing entry and optionally push.
.PARAMETER Entry The entry object returned by Add-McpSessionEntry.
.PARAMETER Session The parent session object.
.PARAMETER Response Updated response text.
.PARAMETER Status Updated status.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][PSCustomObject]$Entry,
[PSCustomObject]$Session,
[string]$Response,
[ValidateSet("in_progress","completed")][string]$Status,
[string[]]$FilesModified,
[string[]]$DesignDecisions,
[switch]$NoPush
)
if ($Response) { $Entry.response = $Response }
if ($Status) { $Entry.status = $Status }
if ($FilesModified) { foreach ($f in $FilesModified) { $Entry.filesModified.Add($f) } }
if ($DesignDecisions) { foreach ($d in $DesignDecisions) { $Entry.designDecisions.Add($d) } }
if ($Session -and -not $NoPush) {
Update-McpSessionLog -Session $Session
}
}
# ─── Actions ─────────────────────────────────────────────────────────────────
function Add-McpAction {
<#
.SYNOPSIS Add an action to a session entry.
.PARAMETER Entry The entry object.
.PARAMETER Description What was done.
.PARAMETER Type Action type: edit, create, delete, commit, design_decision, etc.
.PARAMETER FilePath Affected file path (empty string if N/A).
.PARAMETER Status "completed", "in_progress", or "failed".
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][PSCustomObject]$Entry,
[Parameter(Mandatory)][string]$Description,
[Parameter(Mandatory)][ValidateSet(
"edit","create","delete","design_decision","commit",
"pr_comment","issue_comment","web_reference",
"dependency_add","license_violation","origin_violation",
"origin_review","entity_violation","copilot_invocation","policy_change"
)][string]$Type,
[string]$FilePath = "",
[ValidateSet("completed","in_progress","failed")][string]$Status = "completed"
)
$action = [PSCustomObject]@{
order = $Entry.actions.Count + 1
description = $Description
type = $Type
status = $Status
filePath = $FilePath
}
$Entry.actions.Add($action)
return $action
}
# ─── Dialog ──────────────────────────────────────────────────────────────────
function Send-McpDialog {
<#
.SYNOPSIS Post reasoning dialog items to the session log dialog endpoint.
.PARAMETER Session The session object.
.PARAMETER RequestId The request entry ID.
.PARAMETER Content The reasoning text or observation.
.PARAMETER Role "model", "tool", "system", or "user".
.PARAMETER Category "reasoning", "tool_call", "tool_result", "observation", or "decision".
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][PSCustomObject]$Session,
[Parameter(Mandatory)][string]$RequestId,
[Parameter(Mandatory)][string]$Content,
[ValidateSet("model","tool","system","user")][string]$Role = "model",
[ValidateSet("reasoning","tool_call","tool_result","observation","decision")][string]$Category = "reasoning"
)
Assert-Initialized
$item = @{
timestamp = (Get-Date).ToUniversalTime().ToString("o")
role = $Role
content = $Content
category = $Category
}
$uri = "$($script:McpBaseUrl)/mcpserver/sessionlog/$($Session.sourceType)/$($Session.sessionId)/$RequestId/dialog"
$body = ConvertTo-Json @($item) -Depth 5
Invoke-RestMethod -Uri $uri -Method Post -Headers $script:McpHeaders -Body $body | Out-Null
}
# ─── Helpers ─────────────────────────────────────────────────────────────────
function Assert-Initialized {
if (-not $script:McpBaseUrl) {
throw "MCP session not initialized. Call Initialize-McpSession first."
}
}
function Push-SessionLog {
param([PSCustomObject]$Session)
$body = $Session | ConvertTo-Json -Depth 10
Invoke-RestMethod -Uri "$($script:McpBaseUrl)/mcpserver/sessionlog" -Method Post -Headers $script:McpHeaders -Body $body | Out-Null
}
# ─── Exports ─────────────────────────────────────────────────────────────────
Export-ModuleMember -Function @(
'Initialize-McpSession',
'New-McpSessionLog',
'Update-McpSessionLog',
'Get-McpSessionLog',
'Add-McpSessionEntry',
'Set-McpSessionEntry',
'Add-McpAction',
'Send-McpDialog'
)