@geohar/pi-mcp-combiner 0.16.0-dev.3 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/client/types.d.ts +6 -1
- package/dist/client/types.d.ts.map +1 -1
- package/dist/client/types.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +30 -52
- package/dist/index.js.map +1 -1
- package/dist/native/combiner-connection.d.ts +31 -9
- package/dist/native/combiner-connection.d.ts.map +1 -1
- package/dist/native/combiner-connection.js +131 -80
- package/dist/native/combiner-connection.js.map +1 -1
- package/dist/native/index.d.ts +8 -4
- package/dist/native/index.d.ts.map +1 -1
- package/dist/native/index.js +24 -18
- package/dist/native/index.js.map +1 -1
- package/dist/native/resources.d.ts +7 -2
- package/dist/native/resources.d.ts.map +1 -1
- package/dist/native/resources.js +21 -3
- package/dist/native/resources.js.map +1 -1
- package/dist/native/tool-surface.d.ts +24 -11
- package/dist/native/tool-surface.d.ts.map +1 -1
- package/dist/native/tool-surface.js +71 -34
- package/dist/native/tool-surface.js.map +1 -1
- package/dist/pi.d.ts +9 -1
- package/dist/pi.d.ts.map +1 -1
- package/package.json +6 -2
- package/src/client/types.ts +4 -1
- package/src/index.ts +31 -51
- package/src/native/combiner-connection.ts +155 -83
- package/src/native/index.ts +34 -24
- package/src/native/resources.ts +34 -5
- package/src/native/tool-surface.ts +103 -46
- package/src/pi.ts +5 -1
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
// path, the optional inbound bearer, tools/prompts/resources caches, one stale-session
|
|
12
12
|
// retry, and the widget log-notification tap.
|
|
13
13
|
//
|
|
14
|
-
// CONTRACT: this class
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
14
|
+
// CONTRACT: this class implements client/types.ts's CombinerConnection interface, so
|
|
15
|
+
// every surface (prompts.ts, resources.ts, footer.ts, panel.ts, control.ts) types
|
|
16
|
+
// against the interface, not against this file. The model-facing difference in native
|
|
17
|
+
// mode is registration: see native/tool-surface.ts — tools are declared to pi NATIVELY
|
|
18
|
+
// (pi.registerTool with exposure/namespace/annotations), and the mcp() router
|
|
19
|
+
// (createMcpTool in index.ts) ALSO rides this same connection — there is no script tool.
|
|
20
20
|
//
|
|
21
21
|
// Why instantiate instead of wrapping: pi's built-in MCP extension owns its client
|
|
22
22
|
// instances privately; no hook reaches them (verified 0.99→1.0). Owning the connection
|
|
@@ -25,8 +25,16 @@
|
|
|
25
25
|
// endgame; this class is what the extension ships until and after that lands.
|
|
26
26
|
|
|
27
27
|
import { appendFileSync } from "node:fs"
|
|
28
|
-
import {
|
|
29
|
-
|
|
28
|
+
import {
|
|
29
|
+
McpClient,
|
|
30
|
+
McpConnectionClosedError,
|
|
31
|
+
McpSessionExpiredError,
|
|
32
|
+
McpTimeoutError,
|
|
33
|
+
StreamableHttpTransport,
|
|
34
|
+
type CallToolResult,
|
|
35
|
+
type McpRequestOptions,
|
|
36
|
+
type McpTransport,
|
|
37
|
+
} from "@earendil-works/pi-mcp"
|
|
30
38
|
import { handleElicitation, type ElicitResponse, type ElicitUi } from "../client/elicitation.js"
|
|
31
39
|
import type { CombinerConnection } from "../client/types.js"
|
|
32
40
|
import type { ServerFilter } from "../client/config-ladder.js"
|
|
@@ -83,7 +91,11 @@ export type ConnectionHooks = {
|
|
|
83
91
|
export type ElicitResult = ElicitResponse
|
|
84
92
|
|
|
85
93
|
|
|
94
|
+
// Debug logging is OPT-IN (env PI_MCP_COMBINER_NC_DBG=1): it writes tool names, session
|
|
95
|
+
// ids and error text to /tmp/pi-combiner-dbg.log. Ships disabled — never on by default.
|
|
96
|
+
const ncDbgEnabled = process.env.PI_MCP_COMBINER_NC_DBG === "1"
|
|
86
97
|
function ncDbg(s: string): void {
|
|
98
|
+
if (!ncDbgEnabled) return
|
|
87
99
|
try {
|
|
88
100
|
appendFileSync("/tmp/pi-combiner-dbg.log", `${new Date().toISOString()} ${s}\n`)
|
|
89
101
|
} catch {
|
|
@@ -91,7 +103,9 @@ function ncDbg(s: string): void {
|
|
|
91
103
|
}
|
|
92
104
|
}
|
|
93
105
|
|
|
94
|
-
|
|
106
|
+
// Keep in sync with plugins/pi/package.json "version": scripts/bump-version.sh stamps
|
|
107
|
+
// this line alongside the package files (the string is what this client declares).
|
|
108
|
+
const CLIENT_INFO = { name: "pi-mcp-combiner", version: "0.16.0" }
|
|
95
109
|
const CONNECT_TIMEOUT_MS = 8_000
|
|
96
110
|
const LIST_CACHE_MS = 5_000
|
|
97
111
|
|
|
@@ -117,6 +131,9 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
117
131
|
private elicitUi: ElicitUi = { hasUI: false }
|
|
118
132
|
private token: string | undefined
|
|
119
133
|
private client: McpClient | undefined
|
|
134
|
+
/** Bumped by every reset: in-flight connects check it before publishing a client
|
|
135
|
+
* (a connect that started before the reset must never win the publish race). */
|
|
136
|
+
private generation = 0
|
|
120
137
|
private connecting: Promise<McpClient> | undefined
|
|
121
138
|
private tools: ToolSummary[] | undefined
|
|
122
139
|
private toolsFetchedAt = 0
|
|
@@ -128,9 +145,15 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
128
145
|
state: ConnectionState = "disconnected"
|
|
129
146
|
lastError: string | undefined
|
|
130
147
|
|
|
131
|
-
|
|
148
|
+
/** Test seam: build the transport for one connect (defaults to
|
|
149
|
+
* StreamableHttpTransport). Injection lets tests drive the connection over an
|
|
150
|
+
* in-memory pair instead of HTTP. */
|
|
151
|
+
private readonly transportFactory: ((url: URL) => McpTransport) | undefined
|
|
152
|
+
|
|
153
|
+
constructor(conn: ResolvedConnection, log: LogFn, opts?: { transportFactory?: (url: URL) => McpTransport }) {
|
|
132
154
|
this.conn = conn
|
|
133
155
|
this.log = log
|
|
156
|
+
this.transportFactory = opts?.transportFactory
|
|
134
157
|
}
|
|
135
158
|
|
|
136
159
|
setHooks(hooks: ConnectionHooks): void {
|
|
@@ -170,6 +193,7 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
170
193
|
|
|
171
194
|
/** Drop the connection + caches (session reset / shutdown). Never throws. */
|
|
172
195
|
async reset(reason: string): Promise<void> {
|
|
196
|
+
this.generation++
|
|
173
197
|
const client = this.client
|
|
174
198
|
this.client = undefined
|
|
175
199
|
this.connecting = undefined
|
|
@@ -207,7 +231,8 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
207
231
|
const bearer = this.conn.bearerTokenEnv ? process.env[this.conn.bearerTokenEnv] : undefined
|
|
208
232
|
|
|
209
233
|
this.state = "connecting"
|
|
210
|
-
|
|
234
|
+
const genAtStart = this.generation
|
|
235
|
+
const connectPromise = (async (): Promise<McpClient> => {
|
|
211
236
|
const client = new McpClient({
|
|
212
237
|
name: CLIENT_INFO.name,
|
|
213
238
|
version: CLIENT_INFO.version,
|
|
@@ -273,17 +298,54 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
273
298
|
}
|
|
274
299
|
})
|
|
275
300
|
|
|
276
|
-
const transport =
|
|
277
|
-
url
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
301
|
+
const transport = this.transportFactory
|
|
302
|
+
? this.transportFactory(url)
|
|
303
|
+
: new StreamableHttpTransport({
|
|
304
|
+
url,
|
|
305
|
+
authProvider: bearer ? { token: async () => bearer } : undefined,
|
|
306
|
+
})
|
|
307
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
308
|
+
const connectP = client.connect(transport)
|
|
309
|
+
const settle = connectP.then((r) => r)
|
|
310
|
+
// Late rejections (close beats connect, timeout raced a slow success) must
|
|
311
|
+
// not become unhandled rejections — pi crashes on those.
|
|
312
|
+
settle.catch(() => undefined)
|
|
313
|
+
try {
|
|
314
|
+
await Promise.race([
|
|
315
|
+
settle,
|
|
316
|
+
new Promise((_, reject) =>
|
|
317
|
+
setTimeout(
|
|
318
|
+
() => reject(new Error(`connect timeout after ${CONNECT_TIMEOUT_MS}ms`)),
|
|
319
|
+
CONNECT_TIMEOUT_MS,
|
|
320
|
+
),
|
|
321
|
+
),
|
|
322
|
+
])
|
|
323
|
+
} catch (e) {
|
|
324
|
+
// The client may STILL complete its connect after this failure (the
|
|
325
|
+
// timeout raced a slow success): close it best-effort, non-blocking, so
|
|
326
|
+
// no untracked SSE stream/handlers compete for the token's elicitation
|
|
327
|
+
// routing (the zombie class the reload teardown also guards).
|
|
328
|
+
void client.close().catch(() => undefined)
|
|
329
|
+
throw e
|
|
330
|
+
} finally {
|
|
331
|
+
if (timer) clearTimeout(timer)
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (this.generation !== genAtStart) {
|
|
335
|
+
// A reset() (setToken/rebind/session switch) ran while this connect was
|
|
336
|
+
// in flight: never publish the laggard — it would resurrect the old
|
|
337
|
+
// token/routing the reset just dropped. Close it; the NEXT
|
|
338
|
+
// ensureConnected builds its own.
|
|
339
|
+
void client.close().catch(() => undefined)
|
|
340
|
+
throw new Error("connect superseded by a connection reset (token/config changed)")
|
|
341
|
+
}
|
|
284
342
|
|
|
285
343
|
this.client = client
|
|
286
|
-
|
|
344
|
+
// SAFETY: pi-mcp's McpClient session id lives only on concrete internals —
|
|
345
|
+
// the casts read it for debug output only; unknown means "unexposed".
|
|
346
|
+
ncDbg(
|
|
347
|
+
`ensureConnected: CONNECTED session=${(client as unknown as { sessionId?: string }).sessionId ?? "?"} state=${(client as unknown as { transport?: { sessionId?: string } }).transport?.sessionId ?? "?"}`,
|
|
348
|
+
)
|
|
287
349
|
this.state = "connected"
|
|
288
350
|
this.lastError = undefined
|
|
289
351
|
// Catch-up after (re)connect — same rationale as client/connection.ts:
|
|
@@ -297,17 +359,25 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
297
359
|
this.hooks.onStateChange?.(this.state)
|
|
298
360
|
return client
|
|
299
361
|
})()
|
|
362
|
+
this.connecting = connectPromise
|
|
300
363
|
|
|
301
364
|
try {
|
|
302
|
-
return await
|
|
365
|
+
return await connectPromise
|
|
303
366
|
} catch (e) {
|
|
304
|
-
this.
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
367
|
+
const superseded = this.generation !== genAtStart
|
|
368
|
+
if (!superseded) {
|
|
369
|
+
this.state = "failed"
|
|
370
|
+
this.lastError = e instanceof Error ? e.message : String(e)
|
|
371
|
+
this.log("warn", `combiner connect failed (${this.lastError})`)
|
|
372
|
+
this.hooks.onStateChange?.(this.state)
|
|
373
|
+
}
|
|
374
|
+
throw superseded
|
|
375
|
+
? e
|
|
376
|
+
: new Error(`cannot reach the combiner at ${this.conn.baseUrl}: ${this.lastError} — the combiner may have restarted; this call did not run and is safe to retry (carried state: grants, filters, parked sessions survives restarts)`)
|
|
309
377
|
} finally {
|
|
310
|
-
|
|
378
|
+
// Identity check: a reset + newer connect may have repopulated
|
|
379
|
+
// this.connecting while we awaited — never wipe the newer single-flight.
|
|
380
|
+
if (this.connecting === connectPromise) this.connecting = undefined
|
|
311
381
|
}
|
|
312
382
|
}
|
|
313
383
|
|
|
@@ -315,22 +385,44 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
315
385
|
* bounce invalidates the transport session, and the first operation to notice
|
|
316
386
|
* can be any of them (the router's listTools lookup runs BEFORE callTool;
|
|
317
387
|
* without this it surfaced raw McpSessionExpiredError and never reset the
|
|
318
|
-
* client, wedging the connection until reload).
|
|
319
|
-
*
|
|
320
|
-
|
|
388
|
+
* client, wedging the connection until reload).
|
|
389
|
+
* Classification is TYPE-based over pi-mcp's exported taxonomy; the message
|
|
390
|
+
* regex remains only as a belt for raw transport failures pi-mcp does not wrap
|
|
391
|
+
* (e.g. fetch failed). callTool passes retryStaleOnly: only
|
|
392
|
+
* McpSessionExpiredError — which the server raises BEFORE executing anything —
|
|
393
|
+
* may trigger an automatic re-run there. */
|
|
394
|
+
private async withStaleRetry<T>(
|
|
395
|
+
label: string,
|
|
396
|
+
op: (client: McpClient) => Promise<T>,
|
|
397
|
+
opts?: { retryStaleOnly?: boolean },
|
|
398
|
+
): Promise<T> {
|
|
321
399
|
const client = await this.ensureConnected()
|
|
322
400
|
try {
|
|
323
401
|
return await op(client)
|
|
324
402
|
} catch (e) {
|
|
325
|
-
const typedStale = e instanceof McpSessionExpiredError
|
|
326
403
|
const msg = e instanceof Error ? e.message : String(e)
|
|
327
|
-
|
|
404
|
+
const staleOnly = opts?.retryStaleOnly === true
|
|
328
405
|
const stale =
|
|
329
|
-
|
|
406
|
+
e instanceof McpSessionExpiredError ||
|
|
407
|
+
(!staleOnly &&
|
|
408
|
+
(e instanceof McpConnectionClosedError ||
|
|
409
|
+
e instanceof McpTimeoutError ||
|
|
410
|
+
/404|stale|session|not found|closed|fetch failed|illegal/i.test(msg)))
|
|
330
411
|
if (!stale) throw e
|
|
331
|
-
ncDbg(`${label} stale-retry FIRED`)
|
|
332
|
-
this.log(
|
|
333
|
-
|
|
412
|
+
ncDbg(`${label} stale-retry FIRED typed=${e instanceof McpSessionExpiredError}`)
|
|
413
|
+
this.log(
|
|
414
|
+
"info",
|
|
415
|
+
`${label} went stale (${e instanceof McpSessionExpiredError ? "session expired" : msg}); reconnecting once`,
|
|
416
|
+
)
|
|
417
|
+
// Reset ONLY if the failing client is still the current one — a concurrent
|
|
418
|
+
// caller may already have reset and reconnected ("detach, don't close" was
|
|
419
|
+
// pi's builtin wording); resetting here would close the FRESH client every
|
|
420
|
+
// in-flight call just reconnected, cascading into another stale round.
|
|
421
|
+
if (this.client === client) {
|
|
422
|
+
await this.reset("stale session")
|
|
423
|
+
} else {
|
|
424
|
+
ncDbg(`${label} skipped reset — client already replaced by a concurrent reset`)
|
|
425
|
+
}
|
|
334
426
|
return await op(await this.ensureConnected())
|
|
335
427
|
}
|
|
336
428
|
}
|
|
@@ -339,7 +431,6 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
339
431
|
* pi-mcp returns the tools array directly (pagination already resolved). */
|
|
340
432
|
async listTools(force = false): Promise<ToolSummary[]> {
|
|
341
433
|
if (!force && this.tools && Date.now() - this.toolsFetchedAt < LIST_CACHE_MS) return this.tools
|
|
342
|
-
const client = await this.ensureConnected()
|
|
343
434
|
const tools: ToolSummary[] = (await this.withStaleRetry("listTools", (c) => c.listTools())).map((t) => ({
|
|
344
435
|
name: t.name,
|
|
345
436
|
description: t.description,
|
|
@@ -390,52 +481,33 @@ export class NativeCombinerConnection implements CombinerConnection {
|
|
|
390
481
|
return this.withStaleRetry(`readResource ${uri}`, (c) => c.readResource(uri))
|
|
391
482
|
}
|
|
392
483
|
|
|
393
|
-
/** callTool
|
|
394
|
-
*
|
|
395
|
-
*
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
ncDbg(`callTool ${name} THROW typed=${typedStale} status=${(e as { status?: number } | null)?.status} ${msg.slice(0, 140)}`)
|
|
421
|
-
const stale = typedStale || /404|stale|session|not found|closed|fetch failed|illegal/i.test(msg)
|
|
422
|
-
if (!stale) throw e
|
|
423
|
-
ncDbg(`callTool ${name} stale-retry FIRED`)
|
|
424
|
-
this.log(
|
|
425
|
-
"info",
|
|
426
|
-
`call "${name}" went stale (${typedStale ? "session expired (typed)" : msg}); reconnecting once`,
|
|
427
|
-
)
|
|
428
|
-
await this.reset("stale session")
|
|
429
|
-
ncDbg(`callTool ${name} reset done; retrying`)
|
|
430
|
-
try {
|
|
431
|
-
const result = await attempt()
|
|
432
|
-
ncDbg(`callTool ${name} RETRY SUCCEEDED`)
|
|
433
|
-
return result
|
|
434
|
-
} catch (e2) {
|
|
435
|
-
ncDbg(`callTool ${name} RETRY FAILED: ${e2 instanceof Error ? e2.message : String(e2)}`)
|
|
436
|
-
throw e2
|
|
437
|
-
}
|
|
438
|
-
}
|
|
484
|
+
/** callTool. Transport-level stale retry is STALE-ONLY (typed
|
|
485
|
+
* McpSessionExpiredError): that error is raised by the server BEFORE it
|
|
486
|
+
* executes the request, so one re-run is provably safe. Any other failure —
|
|
487
|
+
* closed/timeout/"fetch failed" AFTER delivery — may correspond to a request
|
|
488
|
+
* that already EXECUTED upstream; an automatic re-run could repeat a
|
|
489
|
+
* destructive tool, so those surface as errors (with the recovery hints) and
|
|
490
|
+
* the model/user decides whether to call again.
|
|
491
|
+
* A server-marked error (CallToolResult.isError) is checked AFTER the transport
|
|
492
|
+
* retry layer and THROWS, so pi records the call as a tool error — and crucially
|
|
493
|
+
* the tool's own error TEXT can never reach the retry classification (a
|
|
494
|
+
* "…not found" tool error must not look like transport staleness).
|
|
495
|
+
* `options.signal` rides into the transport: cancellation cancels upstream work
|
|
496
|
+
* and widget holds (notifications/cancelled). */
|
|
497
|
+
async callTool(
|
|
498
|
+
name: string,
|
|
499
|
+
args: Record<string, unknown> | undefined,
|
|
500
|
+
options?: McpRequestOptions,
|
|
501
|
+
): Promise<CallToolResult> {
|
|
502
|
+
const result = await this.withStaleRetry(`callTool ${name}`, (c) => c.callTool(name, args, options), {
|
|
503
|
+
retryStaleOnly: true,
|
|
504
|
+
})
|
|
505
|
+
if (!result.isError) return result
|
|
506
|
+
const text = (result.content ?? [])
|
|
507
|
+
.map((b) => (isRecord(b) && b.type === "text" && typeof b.text === "string" ? b.text : JSON.stringify(b)))
|
|
508
|
+
.filter(Boolean)
|
|
509
|
+
.join("\n")
|
|
510
|
+
throw new Error(`combiner tool error (${name}): ${text}`)
|
|
439
511
|
}
|
|
440
512
|
|
|
441
513
|
// ── control plane (unchanged from client/connection.ts) ─────────────────────────
|
package/src/native/index.ts
CHANGED
|
@@ -1,32 +1,34 @@
|
|
|
1
1
|
// NATIVE MODE : activation entry for the
|
|
2
2
|
// pi-mcp-based combiner connection + native tool surface. This file exists so the
|
|
3
|
-
// wire-in stays a few lines in src/index.ts
|
|
3
|
+
// wire-in stays a few lines in src/index.ts:
|
|
4
4
|
//
|
|
5
|
-
// const
|
|
6
|
-
// const
|
|
7
|
-
//
|
|
8
|
-
// if (native) void activateNativeTools(pi, { connection: conn, ... }) as needed
|
|
5
|
+
// const conn = new NativeCombinerConnection(…, clientLog) // implements CombinerConnection
|
|
6
|
+
// const nativeSurface = activateNativeMode(pi, { connection: conn, … })
|
|
7
|
+
// … nativeSurface.run() at session_start (post-setToken) and on list_changed
|
|
9
8
|
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
9
|
+
// The FIRST run is deferred by design (see activateNativeMode): the grouping token
|
|
10
|
+
// only exists after session_start. Configuration (directTools spec, server filter)
|
|
11
|
+
// rides as GETTERS so every pass resolves the CURRENT session's values — worktree
|
|
12
|
+
// and project switches re-resolve session config, and a load-time snapshot would
|
|
13
|
+
// apply the wrong allow/deny set to later sessions (review finding #5).
|
|
14
14
|
|
|
15
15
|
import type { ExtensionAPI, ExtensionContext } from "../pi.js"
|
|
16
16
|
import type { ServerFilter } from "../client/config-ladder.js"
|
|
17
17
|
import { NativeCombinerConnection } from "./combiner-connection.js"
|
|
18
|
-
import { activateNativeTools } from "./tool-surface.js"
|
|
18
|
+
import { activateNativeTools, type NativeToolSurfaceState } from "./tool-surface.js"
|
|
19
19
|
import { activateNativeResources } from "./resources.js"
|
|
20
20
|
|
|
21
21
|
export { NativeCombinerConnection } from "./combiner-connection.js"
|
|
22
|
-
export { activateNativeTools, type NativeToolSurfaceOptions } from "./tool-surface.js"
|
|
22
|
+
export { activateNativeTools, type NativeToolSurfaceOptions, type NativeToolSurfaceState } from "./tool-surface.js"
|
|
23
23
|
export { tokenedUrl } from "./combiner-connection.js"
|
|
24
24
|
export { activateNativeResources, filterInteractiveResources, type NativeResourceOptions } from "./resources.js"
|
|
25
25
|
|
|
26
26
|
export type NativeActivationOptions = {
|
|
27
27
|
connection: NativeCombinerConnection
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
/** Per-project directTools spec, resolved PER PASS (not a load-time snapshot). */
|
|
29
|
+
directSpec?: () => string[] | "search" | undefined
|
|
30
|
+
/** Per-project server filter, resolved PER PASS (same reason). */
|
|
31
|
+
serverFilter?: () => ServerFilter | undefined
|
|
30
32
|
/** Register the interactive read_<resource> tools (index.ts's exposeResources
|
|
31
33
|
* setting); default true. */
|
|
32
34
|
exposeResources?: boolean
|
|
@@ -40,34 +42,42 @@ export type NativeActivationOptions = {
|
|
|
40
42
|
|
|
41
43
|
/** Register the declared tool surface + interactive-resource read_* tools + the
|
|
42
44
|
* list_changed re-registration handler. Called once at session_start; the
|
|
43
|
-
* list_changed hook re-syncs both surfaces on the same names.
|
|
45
|
+
* list_changed hook re-syncs both surfaces on the same names. One shared
|
|
46
|
+
* NativeToolSurfaceState diff across all passes — unchanged declarations are
|
|
47
|
+
* skipped, removed ones re-registered hidden (see activateNativeTools). */
|
|
44
48
|
export function activateNativeMode(
|
|
45
49
|
pi: ExtensionAPI,
|
|
46
50
|
opts: NativeActivationOptions,
|
|
47
51
|
): { run(): void; dispose(): void } {
|
|
48
|
-
const resourceRegistered = new Set<string>()
|
|
49
52
|
let active = true
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
log: opts.log,
|
|
55
|
-
}
|
|
53
|
+
const toolState: NativeToolSurfaceState = { names: new Set(), signatures: new Map() }
|
|
54
|
+
// Cross-pass memory for the read_* tools (skip re-registration of unchanged
|
|
55
|
+
// names — pi.registerTool replaces-by-name with a warning).
|
|
56
|
+
const resourceRegistered = new Set<string>()
|
|
56
57
|
const run = () => {
|
|
57
58
|
if (!active) return
|
|
58
59
|
void activateNativeTools(pi, {
|
|
59
60
|
connection: opts.connection,
|
|
60
61
|
serverFilter: opts.serverFilter,
|
|
61
62
|
directSpec: opts.directSpec,
|
|
63
|
+
state: toolState,
|
|
62
64
|
warnLargeDirectExposure: opts.warnLargeDirectExposure,
|
|
63
65
|
log: opts.log,
|
|
64
66
|
}).catch((e) =>
|
|
65
67
|
opts.log("warn", `native tool surface failed: ${e instanceof Error ? e.message : String(e)}`),
|
|
66
68
|
)
|
|
67
69
|
if (opts.exposeResources !== false) {
|
|
68
|
-
void activateNativeResources(
|
|
69
|
-
|
|
70
|
-
|
|
70
|
+
void activateNativeResources(
|
|
71
|
+
pi,
|
|
72
|
+
{
|
|
73
|
+
connection: opts.connection,
|
|
74
|
+
serverFilter: opts.serverFilter,
|
|
75
|
+
directSpec: opts.directSpec,
|
|
76
|
+
uiAutoOpen: opts.uiAutoOpen,
|
|
77
|
+
log: opts.log,
|
|
78
|
+
},
|
|
79
|
+
resourceRegistered,
|
|
80
|
+
).catch((e) => opts.log("warn", `native resource surface failed: ${e instanceof Error ? e.message : String(e)}`))
|
|
71
81
|
}
|
|
72
82
|
}
|
|
73
83
|
// The FIRST run is the caller's to schedule: the grouping token only exists
|
package/src/native/resources.ts
CHANGED
|
@@ -27,13 +27,25 @@ import type { ServerFilter } from "../client/config-ladder.js"
|
|
|
27
27
|
|
|
28
28
|
export type NativeResourceOptions = {
|
|
29
29
|
connection: NativeCombinerConnection
|
|
30
|
-
/** Per-project server filter, same semantics as legacy filterResources
|
|
31
|
-
|
|
30
|
+
/** Per-project server filter, same semantics as legacy filterResources; a getter
|
|
31
|
+
* resolves per call (worktrees/project switches re-resolve session config). */
|
|
32
|
+
serverFilter?: ServerFilter | (() => ServerFilter | undefined)
|
|
33
|
+
/** The directTools spec (same vocabulary as the tool surface): a read_* tool whose
|
|
34
|
+
* name matches the allowlist is declared "direct", otherwise codemode — consistent
|
|
35
|
+
* with how regular tools are exposed (a getter resolves per call). */
|
|
36
|
+
directSpec?: string[] | "search" | (() => string[] | "search" | undefined)
|
|
32
37
|
/** Auto-open the widget URL on read (index.ts's uiAutoOpen setting). */
|
|
33
38
|
uiAutoOpen?: boolean
|
|
34
39
|
log: (level: "info" | "warn" | "error", message: string) => void
|
|
35
40
|
}
|
|
36
41
|
|
|
42
|
+
function resolveFilter(f: NativeResourceOptions["serverFilter"]): ServerFilter | undefined {
|
|
43
|
+
return typeof f === "function" ? f() : f
|
|
44
|
+
}
|
|
45
|
+
function resolveDirectSpec(d: NativeResourceOptions["directSpec"]): string[] | "search" | undefined {
|
|
46
|
+
return typeof d === "function" ? d() : d
|
|
47
|
+
}
|
|
48
|
+
|
|
37
49
|
/** Project server filter for resources — mirrors legacy filterResources
|
|
38
50
|
* attribution semantics (uri host first, `<server>_` name-prefix fallback). */
|
|
39
51
|
export function filterInteractiveResources(
|
|
@@ -51,9 +63,21 @@ export function filterInteractiveResources(
|
|
|
51
63
|
return interactive
|
|
52
64
|
}
|
|
53
65
|
|
|
66
|
+
function resolveResourceExposure(
|
|
67
|
+
opts: NativeResourceOptions,
|
|
68
|
+
toolName: string,
|
|
69
|
+
): NonNullable<ToolDefinition["exposure"]> {
|
|
70
|
+
const spec = resolveDirectSpec(opts.directSpec)
|
|
71
|
+
return Array.isArray(spec) && spec.some((p) => matchesResourceGlob(toolName, p)) ? "direct" : "codemode"
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function matchesResourceGlob(name: string, pattern: string): boolean {
|
|
75
|
+
// Same glob vocabulary as the tool surface (matchesGlob from tool-matching).
|
|
76
|
+
return name === pattern || (pattern.endsWith("*") && name.startsWith(pattern.slice(0, -1)))
|
|
77
|
+
}
|
|
78
|
+
|
|
54
79
|
function toReadTool(toolName: string, resource: ResourceSummary, opts: NativeResourceOptions): ToolDefinition {
|
|
55
80
|
const label = resource.name ?? resource.uri
|
|
56
|
-
const url = opts.connection.uiUrlFor(resource.uri)
|
|
57
81
|
return {
|
|
58
82
|
name: toolName,
|
|
59
83
|
label: `MCP resource: ${label}`,
|
|
@@ -67,11 +91,16 @@ function toReadTool(toolName: string, resource: ResourceSummary, opts: NativeRes
|
|
|
67
91
|
.join(" | "),
|
|
68
92
|
promptSnippet: `Read MCP resource ${label}.`,
|
|
69
93
|
parameters: { type: "object", properties: {} },
|
|
70
|
-
exposure:
|
|
94
|
+
exposure: resolveResourceExposure(opts, toolName),
|
|
71
95
|
namespace: { name: "mcp_combiner", description: "mcp-combiner aggregated tools" },
|
|
72
96
|
execute: async (_toolCallId, _params, _signal, _onUpdate, ctx) => {
|
|
73
97
|
try {
|
|
74
98
|
const result = await opts.connection.readResource(resource.uri)
|
|
99
|
+
// Compute the URL PER CALL: the session token changes across /new and
|
|
100
|
+
// resume, and the registered set skips re-registration — a
|
|
101
|
+
// registration-time URL would carry a dead token after the first
|
|
102
|
+
// session switch.
|
|
103
|
+
const url = opts.connection.uiUrlFor(resource.uri)
|
|
75
104
|
let text = renderResourceResult(result)
|
|
76
105
|
if (url) {
|
|
77
106
|
text = `${text}\n\ninteractive: ${url}`
|
|
@@ -94,7 +123,7 @@ export async function activateNativeResources(
|
|
|
94
123
|
): Promise<string[]> {
|
|
95
124
|
let resources: ResourceSummary[] = []
|
|
96
125
|
try {
|
|
97
|
-
resources = filterInteractiveResources(await opts.connection.listResources(true), opts.serverFilter)
|
|
126
|
+
resources = filterInteractiveResources(await opts.connection.listResources(true), resolveFilter(opts.serverFilter))
|
|
98
127
|
} catch (e) {
|
|
99
128
|
opts.log("warn", `interactive resource discovery failed (${e instanceof Error ? e.message : String(e)})`)
|
|
100
129
|
return []
|