@fgv/ts-extras-mcp 5.1.0-36 → 5.1.0-39
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/.rush/temp/{2577843c5e34e6afdd66a491b876db932e6402dc.tar.log → 28abef25194b96c733b5ec1c8816ab85532589aa.tar.log} +2 -2
- package/.rush/temp/chunked-rush-logs/ts-extras-mcp.build.chunks.jsonl +4 -4
- package/.rush/temp/operation/build/all.log +4 -4
- package/.rush/temp/operation/build/log-chunks.jsonl +4 -4
- package/.rush/temp/operation/build/state.json +1 -1
- package/.rush/temp/shrinkwrap-deps.json +227 -226
- package/config/jest.config.json +1 -1
- package/dist/packlets/mcp/adapter.js +2 -7
- package/dist/packlets/mcp/adapter.js.map +1 -1
- package/dist/packlets/mcp/model.js.map +1 -1
- package/dist/packlets/mcp/operations.js +31 -6
- package/dist/packlets/mcp/operations.js.map +1 -1
- package/dist/packlets/mcp/sdk.js.map +1 -1
- package/dist/test/unit/mcp.test.js +113 -0
- package/dist/test/unit/mcp.test.js.map +1 -1
- package/dist/ts-extras-mcp.d.ts +31 -0
- package/dist/tsdoc-metadata.json +1 -1
- package/etc/ts-extras-mcp.api.md +10 -0
- package/lib/packlets/mcp/adapter.d.ts.map +1 -1
- package/lib/packlets/mcp/adapter.js +2 -7
- package/lib/packlets/mcp/adapter.js.map +1 -1
- package/lib/packlets/mcp/model.d.ts +30 -0
- package/lib/packlets/mcp/model.d.ts.map +1 -1
- package/lib/packlets/mcp/model.js.map +1 -1
- package/lib/packlets/mcp/operations.d.ts.map +1 -1
- package/lib/packlets/mcp/operations.js +30 -5
- package/lib/packlets/mcp/operations.js.map +1 -1
- package/lib/packlets/mcp/sdk.d.ts +6 -0
- package/lib/packlets/mcp/sdk.d.ts.map +1 -1
- package/lib/packlets/mcp/sdk.js.map +1 -1
- package/lib/test/unit/mcp.test.js +113 -0
- package/lib/test/unit/mcp.test.js.map +1 -1
- package/package.json +9 -9
- package/rush-logs/ts-extras-mcp.build.cache.log +1 -1
- package/rush-logs/ts-extras-mcp.build.log +4 -4
- package/src/packlets/mcp/adapter.ts +5 -2
- package/src/packlets/mcp/model.ts +31 -0
- package/src/packlets/mcp/operations.ts +46 -3
- package/src/packlets/mcp/sdk.ts +6 -0
- package/src/test/unit/mcp.test.ts +128 -0
- package/temp/build/lint/_eslint-5eVG3S6w.json +6 -6
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/ts-extras-mcp.api.json +182 -1
- package/temp/ts-extras-mcp.api.md +10 -0
package/dist/ts-extras-mcp.d.ts
CHANGED
|
@@ -232,6 +232,31 @@ export declare interface IMcpStdioTransportParams {
|
|
|
232
232
|
readonly cwd?: string;
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
+
/**
|
|
236
|
+
* Normalized MCP `Tool.annotations` — the five known host-advisory behavior hints.
|
|
237
|
+
*
|
|
238
|
+
* @remarks
|
|
239
|
+
* Field names mirror MCP's `ToolAnnotations` 1:1 (and map straight onto
|
|
240
|
+
* `AiAssist.IAiToolAnnotations`). Per the MCP spec these are hints only, and per the
|
|
241
|
+
* untrusted-server warning they are validated/normalized (known fields kept, malformed
|
|
242
|
+
* or unknown fields dropped) before they reach {@link IMcpToolDescriptor} — the raw
|
|
243
|
+
* server blob is never propagated.
|
|
244
|
+
*
|
|
245
|
+
* @public
|
|
246
|
+
*/
|
|
247
|
+
export declare interface IMcpToolAnnotations {
|
|
248
|
+
/** Optional human-readable display title for the tool. */
|
|
249
|
+
readonly title?: string;
|
|
250
|
+
/** Hint: the tool does not modify its environment (read-only). */
|
|
251
|
+
readonly readOnlyHint?: boolean;
|
|
252
|
+
/** Hint: the tool may perform destructive updates (only meaningful when not read-only). */
|
|
253
|
+
readonly destructiveHint?: boolean;
|
|
254
|
+
/** Hint: repeated calls with the same arguments have no additional effect. */
|
|
255
|
+
readonly idempotentHint?: boolean;
|
|
256
|
+
/** Hint: the tool interacts with an open world of external entities. */
|
|
257
|
+
readonly openWorldHint?: boolean;
|
|
258
|
+
}
|
|
259
|
+
|
|
235
260
|
/**
|
|
236
261
|
* Successful projection of an MCP `CallToolResult` produced by {@link callMcpTool}.
|
|
237
262
|
*
|
|
@@ -264,6 +289,12 @@ export declare interface IMcpToolDescriptor {
|
|
|
264
289
|
* supported subset).
|
|
265
290
|
*/
|
|
266
291
|
readonly inputSchema: JsonValue;
|
|
292
|
+
/**
|
|
293
|
+
* The tool's normalized behavior annotations, when the server provided any usable ones.
|
|
294
|
+
* Absent when the server declared no annotations (or only malformed/unknown fields).
|
|
295
|
+
* See {@link IMcpToolAnnotations}.
|
|
296
|
+
*/
|
|
297
|
+
readonly annotations?: IMcpToolAnnotations;
|
|
267
298
|
}
|
|
268
299
|
|
|
269
300
|
/**
|
package/dist/tsdoc-metadata.json
CHANGED
package/etc/ts-extras-mcp.api.md
CHANGED
|
@@ -81,6 +81,15 @@ export interface IMcpStdioTransportParams {
|
|
|
81
81
|
readonly env?: Record<string, string>;
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
// @public
|
|
85
|
+
export interface IMcpToolAnnotations {
|
|
86
|
+
readonly destructiveHint?: boolean;
|
|
87
|
+
readonly idempotentHint?: boolean;
|
|
88
|
+
readonly openWorldHint?: boolean;
|
|
89
|
+
readonly readOnlyHint?: boolean;
|
|
90
|
+
readonly title?: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
84
93
|
// @public
|
|
85
94
|
export interface IMcpToolCallResult {
|
|
86
95
|
readonly content: string;
|
|
@@ -88,6 +97,7 @@ export interface IMcpToolCallResult {
|
|
|
88
97
|
|
|
89
98
|
// @public
|
|
90
99
|
export interface IMcpToolDescriptor {
|
|
100
|
+
readonly annotations?: IMcpToolAnnotations;
|
|
91
101
|
readonly description: string | undefined;
|
|
92
102
|
readonly inputSchema: JsonValue;
|
|
93
103
|
readonly name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../src/packlets/mcp/adapter.ts"],"names":[],"mappings":"AAsBA;;;;;GAKG;AAEH,OAAO,EAAE,KAAK,MAAM,EAAW,MAAM,eAAe,CAAC;AAIrD,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAGjB,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../src/packlets/mcp/adapter.ts"],"names":[],"mappings":"AAsBA;;;;;GAKG;AAEH,OAAO,EAAE,KAAK,MAAM,EAAW,MAAM,eAAe,CAAC;AAIrD,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAGjB,MAAM,SAAS,CAAC;AAkEjB;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,qBAAqB,GAC9B,OAAO,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC,CAuBvC"}
|
|
@@ -53,7 +53,7 @@ function _makeExecute(session, name) {
|
|
|
53
53
|
* tool's `inputSchema` is not a JSON object or is outside the `JsonSchema.fromJson` subset.
|
|
54
54
|
*/
|
|
55
55
|
function _adaptOne(session, descriptor) {
|
|
56
|
-
const { name, description, inputSchema } = descriptor;
|
|
56
|
+
const { name, description, inputSchema, annotations } = descriptor;
|
|
57
57
|
const skip = (reason, schema) => ({
|
|
58
58
|
kind: 'skipped',
|
|
59
59
|
skipped: { name, reason, schema }
|
|
@@ -66,12 +66,7 @@ function _adaptOne(session, descriptor) {
|
|
|
66
66
|
if (schemaResult.isFailure()) {
|
|
67
67
|
return skip(schemaResult.message, inputSchema);
|
|
68
68
|
}
|
|
69
|
-
const config = {
|
|
70
|
-
type: 'client_tool',
|
|
71
|
-
name,
|
|
72
|
-
description: description !== null && description !== void 0 ? description : name,
|
|
73
|
-
parametersSchema: schemaResult.value
|
|
74
|
-
};
|
|
69
|
+
const config = Object.assign({ type: 'client_tool', name, description: description !== null && description !== void 0 ? description : name, parametersSchema: schemaResult.value }, (annotations !== undefined ? { annotations } : {}));
|
|
75
70
|
return {
|
|
76
71
|
kind: 'tool',
|
|
77
72
|
tool: { config, execute: _makeExecute(session, name) }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../../src/packlets/mcp/adapter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;
|
|
1
|
+
{"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../../src/packlets/mcp/adapter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;AA4GH,sCA0BC;AApID;;;;;GAKG;AAEH,4CAAqD;AAErD,oDAA2E;AAS3E,6CAAyD;AAUzD;;;;;GAKG;AACH,SAAS,YAAY,CAAC,OAAoB,EAAE,IAAY;IACtD,OAAO,KAAK,EAAE,IAAa,EAA4B,EAAE;QACvD,MAAM,SAAS,GAAG,yBAAU,CAAC,UAAU;aACpC,OAAO,CAAC,IAAI,CAAC;aACb,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,SAAS,IAAI,uCAAuC,GAAG,EAAE,CAAC,CAAC;QACvF,IAAI,SAAS,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,CAAC,MAAM,IAAA,wBAAW,EAAC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;IAC5G,CAAC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAS,SAAS,CAAC,OAAoB,EAAE,UAA8B;IACrE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,UAAU,CAAC;IA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B,EAAE,CAAC;QAC3C,MAAM,OAAO,GAAsB,EAAE,CAAC;QAEtC,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;YACrC,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;YAC/C,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBAC5B,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YAC3B,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;gBAC9B,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,0CAAE,IAAI,CACnB,uBAAuB,OAAO,CAAC,OAAO,CAAC,IAAI,0CAA0C;oBACnF,uBAAuB,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI;oBACjD,eAAe,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAC1D,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,IAAA,kBAAO,EAAuB,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAC3D,CAAC,CAAC;SACD,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,kBAAkB,GAAG,EAAE,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * The headline adapter — discovers an MCP server's tools and adapts each into an\n * `AiAssist.IAiClientTool`, gracefully degrading (Constraint 1) on any tool whose `inputSchema`\n * is outside the JSON Schema subset that `JsonSchema.fromJson` supports.\n * @packageDocumentation\n */\n\nimport { type Result, succeed } from '@fgv/ts-utils';\nimport { AiAssist } from '@fgv/ts-extras';\nimport { Converters, JsonSchema, type JsonValue } from '@fgv/ts-json-base';\n\nimport {\n type IAdaptMcpToolsOptions,\n type IAdaptMcpToolsResult,\n type IMcpSession,\n type IMcpSkippedTool,\n type IMcpToolDescriptor\n} from './model';\nimport { callMcpTool, listMcpTools } from './operations';\n\n/**\n * Per-tool adaptation outcome: either an adapted client tool, or a structurally-surfaced skip.\n * `adaptMcpTools` never short-circuits on a skip — degradation is structural, not a failure.\n */\ntype IAdaptOutcome =\n | { readonly kind: 'tool'; readonly tool: AiAssist.IAiClientTool }\n | { readonly kind: 'skipped'; readonly skipped: IMcpSkippedTool };\n\n/**\n * Builds the `execute` callback for an adapted MCP tool. Args arrive already validated against\n * the tool's `parametersSchema` by `executeClientToolTurn`; here we narrow to a `JsonObject`\n * (MCP arguments are always an object) and forward to {@link callMcpTool}, returning the\n * projected text content. A tool error surfaces as a `Failure` (never swallowed).\n */\nfunction _makeExecute(session: IMcpSession, name: string): (args: unknown) => Promise<Result<unknown>> {\n return async (args: unknown): Promise<Result<unknown>> => {\n const objResult = Converters.jsonObject\n .convert(args)\n .withErrorFormat((msg) => `tool '${name}': arguments must be a JSON object: ${msg}`);\n if (objResult.isFailure()) {\n return objResult;\n }\n return (await callMcpTool(session, name, objResult.value)).onSuccess((called) => succeed(called.content));\n };\n}\n\n/**\n * Adapts a single discovered tool. Returns a `skipped` outcome (never a failure) when the\n * tool's `inputSchema` is not a JSON object or is outside the `JsonSchema.fromJson` subset.\n */\nfunction _adaptOne(session: IMcpSession, descriptor: IMcpToolDescriptor): IAdaptOutcome {\n const { name, description, inputSchema, annotations } = descriptor;\n\n const skip = (reason: string, schema: JsonValue): IAdaptOutcome => ({\n kind: 'skipped',\n skipped: { name, reason, schema }\n });\n\n const asObject = Converters.jsonObject.convert(inputSchema);\n if (asObject.isFailure()) {\n return skip(`inputSchema is not a JSON object (${asObject.message})`, inputSchema);\n }\n\n const schemaResult = JsonSchema.fromJson(asObject.value);\n if (schemaResult.isFailure()) {\n return skip(schemaResult.message, inputSchema);\n }\n\n const config: AiAssist.IAiClientToolConfig = {\n type: 'client_tool',\n name,\n description: description ?? name,\n parametersSchema: schemaResult.value,\n // IMcpToolAnnotations maps 1:1 onto AiAssist.IAiToolAnnotations. Only set the field when the\n // server provided usable annotations, so a tool without them stays exactly as before.\n ...(annotations !== undefined ? { annotations } : {})\n };\n return {\n kind: 'tool',\n tool: { config, execute: _makeExecute(session, name) }\n };\n}\n\n/**\n * Discovers an MCP server's tools and adapts each into an `AiAssist.IAiClientTool` that drops\n * directly into `AiAssist.executeClientToolTurn`.\n *\n * @remarks\n * **Constraint 1 — graceful degradation with NOISY warnings.** A tool whose `inputSchema` is\n * outside the JSON Schema subset supported by `JsonSchema.fromJson` is NOT adapted (the model\n * must never be offered a tool whose args we can't validate). Instead it is:\n * 1. excluded from {@link IAdaptMcpToolsResult.tools};\n * 2. surfaced structurally on {@link IAdaptMcpToolsResult.skipped} with the tool name, the\n * JSON-pointer reason, and the raw failing schema; and\n * 3. logged as a NOISY `warning` (name + reason + raw schema) when an `options.logger` is\n * supplied — so pointing this at a new server immediately reveals every subset feature to\n * extend, with the schema in hand.\n *\n * The whole catalog never fails on a single bad schema; the only failure mode is an upstream\n * `listMcpTools` error.\n *\n * @param session - A connected session from `connectMcpSession`.\n * @param options - Optional logger for the NOISY skip warnings.\n * @returns `Success` with `{ tools, skipped }`, or `Failure` only if tool discovery fails.\n * @public\n */\nexport async function adaptMcpTools(\n session: IMcpSession,\n options?: IAdaptMcpToolsOptions\n): Promise<Result<IAdaptMcpToolsResult>> {\n return (await listMcpTools(session))\n .onSuccess((descriptors) => {\n const tools: AiAssist.IAiClientTool[] = [];\n const skipped: IMcpSkippedTool[] = [];\n\n for (const descriptor of descriptors) {\n const outcome = _adaptOne(session, descriptor);\n if (outcome.kind === 'tool') {\n tools.push(outcome.tool);\n } else {\n skipped.push(outcome.skipped);\n options?.logger?.warn(\n `mcp: skipping tool '${outcome.skipped.name}': inputSchema is outside the supported ` +\n `JSON Schema subset: ${outcome.skipped.reason}. ` +\n `Raw schema: ${JSON.stringify(outcome.skipped.schema)}`\n );\n }\n }\n\n return succeed<IAdaptMcpToolsResult>({ tools, skipped });\n })\n .withErrorFormat((msg) => `adaptMcpTools: ${msg}`);\n}\n"]}
|
|
@@ -82,6 +82,30 @@ export interface IMcpSession {
|
|
|
82
82
|
/** Server identity reported by the handshake, when the server provided one. */
|
|
83
83
|
readonly serverInfo: IMcpServerInfo | undefined;
|
|
84
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* Normalized MCP `Tool.annotations` — the five known host-advisory behavior hints.
|
|
87
|
+
*
|
|
88
|
+
* @remarks
|
|
89
|
+
* Field names mirror MCP's `ToolAnnotations` 1:1 (and map straight onto
|
|
90
|
+
* `AiAssist.IAiToolAnnotations`). Per the MCP spec these are hints only, and per the
|
|
91
|
+
* untrusted-server warning they are validated/normalized (known fields kept, malformed
|
|
92
|
+
* or unknown fields dropped) before they reach {@link IMcpToolDescriptor} — the raw
|
|
93
|
+
* server blob is never propagated.
|
|
94
|
+
*
|
|
95
|
+
* @public
|
|
96
|
+
*/
|
|
97
|
+
export interface IMcpToolAnnotations {
|
|
98
|
+
/** Optional human-readable display title for the tool. */
|
|
99
|
+
readonly title?: string;
|
|
100
|
+
/** Hint: the tool does not modify its environment (read-only). */
|
|
101
|
+
readonly readOnlyHint?: boolean;
|
|
102
|
+
/** Hint: the tool may perform destructive updates (only meaningful when not read-only). */
|
|
103
|
+
readonly destructiveHint?: boolean;
|
|
104
|
+
/** Hint: repeated calls with the same arguments have no additional effect. */
|
|
105
|
+
readonly idempotentHint?: boolean;
|
|
106
|
+
/** Hint: the tool interacts with an open world of external entities. */
|
|
107
|
+
readonly openWorldHint?: boolean;
|
|
108
|
+
}
|
|
85
109
|
/**
|
|
86
110
|
* A tool descriptor discovered from an MCP server via {@link listMcpTools}.
|
|
87
111
|
* @public
|
|
@@ -98,6 +122,12 @@ export interface IMcpToolDescriptor {
|
|
|
98
122
|
* supported subset).
|
|
99
123
|
*/
|
|
100
124
|
readonly inputSchema: JsonValue;
|
|
125
|
+
/**
|
|
126
|
+
* The tool's normalized behavior annotations, when the server provided any usable ones.
|
|
127
|
+
* Absent when the server declared no annotations (or only malformed/unknown fields).
|
|
128
|
+
* See {@link IMcpToolAnnotations}.
|
|
129
|
+
*/
|
|
130
|
+
readonly annotations?: IMcpToolAnnotations;
|
|
101
131
|
}
|
|
102
132
|
/**
|
|
103
133
|
* Successful projection of an MCP `CallToolResult` produced by {@link callMcpTool}.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../src/packlets/mcp/model.ts"],"names":[],"mappings":"AAsBA;;;GAGG;AAEH,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAMnD;;;;;;;;;GASG;AACH,MAAM,WAAW,wBAAwB;IACvC,sEAAsE;IACtE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;I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AKG;IACH,QAAQ,CAAC,WAAW,EAAE,SAAS,CAAC;IAChC;;;;OAIG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,mBAAmB,CAAC;CAC5C;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,kBAAkB;IACjC,qDAAqD;IACrD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAMD;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,uBAAuB;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,6GAA6G;IAC7G,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,qGAAqG;IACrG,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC;CACnC;AAED;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC,6FAA6F;IAC7F,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;IACtD,8FAA8F;IAC9F,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC,eAAe,CAAC,CAAC;CAClD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../../src/packlets/mcp/model.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Public types for the MCP → ai-assist client-tools boundary.\n * @packageDocumentation\n */\n\nimport { type Logging } from '@fgv/ts-utils';\nimport { type AiAssist } from '@fgv/ts-extras';\nimport { type JsonValue } from '@fgv/ts-json-base';\n\n// ============================================================================\n// Transport\n// ============================================================================\n\n/**\n * Parameters for {@link createStdioTransport}. The transport spawns `command` as a\n * subprocess and speaks MCP over its stdin/stdout.\n *\n * @remarks\n * **Security:** stdio transport executes a consumer-supplied command. Treat `command`/`args`\n * as a trust boundary — never source them from untrusted input. See the package README.\n *\n * @public\n */\nexport interface IMcpStdioTransportParams {\n /** Executable to spawn (e.g. `'npx'`, `'node'`, an absolute path). */\n readonly command: string;\n /** Arguments passed to the command. */\n readonly args?: ReadonlyArray<string>;\n /** Environment variables for the spawned process. When omitted, the SDK's safe default set is used. */\n readonly env?: Record<string, string>;\n /** Working directory for the spawned process. */\n readonly cwd?: string;\n}\n\n/**\n * Parameters for {@link createHttpTransport}. The transport connects to a Streamable-HTTP MCP\n * endpoint.\n * @public\n */\nexport interface IMcpHttpTransportParams {\n /** Absolute `http`/`https` URL of the MCP server endpoint. */\n readonly url: string;\n /** Optional static headers (e.g. an `Authorization` bearer token). OAuth/managed auth is out of scope at v0.1. */\n readonly headers?: Record<string, string>;\n}\n\n/**\n * Opaque handle to an MCP transport produced by {@link createStdioTransport} or\n * {@link createHttpTransport}. Hand it to {@link connectMcpSession}; do not construct directly.\n * @public\n */\nexport interface IMcpTransport {\n /** Which transport kind this handle wraps. */\n readonly transportKind: 'stdio' | 'http';\n}\n\n// ============================================================================\n// Session\n// ============================================================================\n\n/**\n * Parameters for {@link connectMcpSession}.\n * @public\n */\nexport interface IConnectMcpSessionParams {\n /** A transport produced by {@link createStdioTransport} / {@link createHttpTransport}. */\n readonly transport: IMcpTransport;\n /** Client name advertised to the server during the initialize handshake. Default `'@fgv/ts-extras-mcp'`. */\n readonly clientName?: string;\n /** Client version advertised to the server. Default the package version. */\n readonly clientVersion?: string;\n /** Optional logger for connection diagnostics. */\n readonly logger?: Logging.ILogger;\n}\n\n/**\n * Server identity reported during the MCP initialize handshake.\n * @public\n */\nexport interface IMcpServerInfo {\n /** Server-advertised name. */\n readonly name: string;\n /** Server-advertised version. */\n readonly version: string;\n}\n\n/**\n * Opaque handle to a connected MCP session. Pass it to {@link listMcpTools},\n * {@link callMcpTool}, {@link adaptMcpTools}, and {@link closeMcpSession}.\n * @public\n */\nexport interface IMcpSession {\n /** Client name advertised during the handshake. */\n readonly clientName: string;\n /** Client version advertised during the handshake. */\n readonly clientVersion: string;\n /** Server identity reported by the handshake, when the server provided one. */\n readonly serverInfo: IMcpServerInfo | undefined;\n}\n\n// ============================================================================\n// Tool discovery + invocation\n// ============================================================================\n\n/**\n * A tool descriptor discovered from an MCP server via {@link listMcpTools}.\n * @public\n */\nexport interface IMcpToolDescriptor {\n /** Tool name (unique within a server). */\n readonly name: string;\n /** Human-readable description, when the server provided one. */\n readonly description: string | undefined;\n /**\n * The tool's declared input schema as raw JSON. Per the MCP spec this is normally a JSON\n * Schema object; carried verbatim so {@link adaptMcpTools} can run it through\n * `JsonSchema.fromJson` (and surface it on {@link IMcpSkippedTool} when it is outside the\n * supported subset).\n */\n readonly inputSchema: JsonValue;\n}\n\n/**\n * Successful projection of an MCP `CallToolResult` produced by {@link callMcpTool}.\n *\n * @remarks\n * `content` is the text concatenation of the result's `text` blocks; non-text blocks\n * (image / audio / resource) are projected to a one-line `[<type> block]` summary\n * (multimodal passthrough is out of scope at v0.1). A result with `isError: true` is mapped\n * to `Result.fail(content)` rather than returned here, so it is never silently swallowed.\n *\n * @public\n */\nexport interface IMcpToolCallResult {\n /** The projected text content of the tool result. */\n readonly content: string;\n}\n\n// ============================================================================\n// Adapter (Constraint 1)\n// ============================================================================\n\n/**\n * A tool that was discovered but could NOT be adapted into an `AiAssist.IAiClientTool`,\n * because its `inputSchema` is outside the JSON Schema subset supported by\n * `JsonSchema.fromJson`. Surfaced structurally so callers/the probe can enumerate exactly which\n * subset features a server needs (with the raw schema in hand to extend `fromJson` later).\n * @public\n */\nexport interface IMcpSkippedTool {\n /** The tool's name. */\n readonly name: string;\n /** Why the tool was skipped — the JSON-pointer reason from `JsonSchema.fromJson`, or a structural reason. */\n readonly reason: string;\n /** The raw failing input schema, verbatim, in hand for additively widening `JsonSchema.fromJson`. */\n readonly schema: JsonValue;\n}\n\n/**\n * Options for {@link adaptMcpTools}.\n * @public\n */\nexport interface IAdaptMcpToolsOptions {\n /**\n * Logger for the NOISY per-tool skip warnings. When a tool is skipped, a `warning` is emitted\n * including the tool name, the JSON-pointer reason, and the raw failing schema. When omitted,\n * skips are still surfaced structurally on {@link IAdaptMcpToolsResult.skipped}.\n */\n readonly logger?: Logging.ILogger;\n}\n\n/**\n * The result of {@link adaptMcpTools}: cleanly-adapted client tools plus the structurally-surfaced\n * set of tools that could not be adapted (graceful degradation, Constraint 1).\n * @public\n */\nexport interface IAdaptMcpToolsResult {\n /** Tools adapted into `IAiClientTool` — safe to hand to `AiAssist.executeClientToolTurn`. */\n readonly tools: ReadonlyArray<AiAssist.IAiClientTool>;\n /** Tools excluded because their `inputSchema` is outside the supported JSON Schema subset. */\n readonly skipped: ReadonlyArray<IMcpSkippedTool>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../../src/packlets/mcp/model.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Public types for the MCP → ai-assist client-tools boundary.\n * @packageDocumentation\n */\n\nimport { type Logging } from '@fgv/ts-utils';\nimport { type AiAssist } from '@fgv/ts-extras';\nimport { type JsonValue } from '@fgv/ts-json-base';\n\n// ============================================================================\n// Transport\n// ============================================================================\n\n/**\n * Parameters for {@link createStdioTransport}. The transport spawns `command` as a\n * subprocess and speaks MCP over its stdin/stdout.\n *\n * @remarks\n * **Security:** stdio transport executes a consumer-supplied command. Treat `command`/`args`\n * as a trust boundary — never source them from untrusted input. See the package README.\n *\n * @public\n */\nexport interface IMcpStdioTransportParams {\n /** Executable to spawn (e.g. `'npx'`, `'node'`, an absolute path). */\n readonly command: string;\n /** Arguments passed to the command. */\n readonly args?: ReadonlyArray<string>;\n /** Environment variables for the spawned process. When omitted, the SDK's safe default set is used. */\n readonly env?: Record<string, string>;\n /** Working directory for the spawned process. */\n readonly cwd?: string;\n}\n\n/**\n * Parameters for {@link createHttpTransport}. The transport connects to a Streamable-HTTP MCP\n * endpoint.\n * @public\n */\nexport interface IMcpHttpTransportParams {\n /** Absolute `http`/`https` URL of the MCP server endpoint. */\n readonly url: string;\n /** Optional static headers (e.g. an `Authorization` bearer token). OAuth/managed auth is out of scope at v0.1. */\n readonly headers?: Record<string, string>;\n}\n\n/**\n * Opaque handle to an MCP transport produced by {@link createStdioTransport} or\n * {@link createHttpTransport}. Hand it to {@link connectMcpSession}; do not construct directly.\n * @public\n */\nexport interface IMcpTransport {\n /** Which transport kind this handle wraps. */\n readonly transportKind: 'stdio' | 'http';\n}\n\n// ============================================================================\n// Session\n// ============================================================================\n\n/**\n * Parameters for {@link connectMcpSession}.\n * @public\n */\nexport interface IConnectMcpSessionParams {\n /** A transport produced by {@link createStdioTransport} / {@link createHttpTransport}. */\n readonly transport: IMcpTransport;\n /** Client name advertised to the server during the initialize handshake. Default `'@fgv/ts-extras-mcp'`. */\n readonly clientName?: string;\n /** Client version advertised to the server. Default the package version. */\n readonly clientVersion?: string;\n /** Optional logger for connection diagnostics. */\n readonly logger?: Logging.ILogger;\n}\n\n/**\n * Server identity reported during the MCP initialize handshake.\n * @public\n */\nexport interface IMcpServerInfo {\n /** Server-advertised name. */\n readonly name: string;\n /** Server-advertised version. */\n readonly version: string;\n}\n\n/**\n * Opaque handle to a connected MCP session. Pass it to {@link listMcpTools},\n * {@link callMcpTool}, {@link adaptMcpTools}, and {@link closeMcpSession}.\n * @public\n */\nexport interface IMcpSession {\n /** Client name advertised during the handshake. */\n readonly clientName: string;\n /** Client version advertised during the handshake. */\n readonly clientVersion: string;\n /** Server identity reported by the handshake, when the server provided one. */\n readonly serverInfo: IMcpServerInfo | undefined;\n}\n\n// ============================================================================\n// Tool discovery + invocation\n// ============================================================================\n\n/**\n * Normalized MCP `Tool.annotations` — the five known host-advisory behavior hints.\n *\n * @remarks\n * Field names mirror MCP's `ToolAnnotations` 1:1 (and map straight onto\n * `AiAssist.IAiToolAnnotations`). Per the MCP spec these are hints only, and per the\n * untrusted-server warning they are validated/normalized (known fields kept, malformed\n * or unknown fields dropped) before they reach {@link IMcpToolDescriptor} — the raw\n * server blob is never propagated.\n *\n * @public\n */\nexport interface IMcpToolAnnotations {\n /** Optional human-readable display title for the tool. */\n readonly title?: string;\n /** Hint: the tool does not modify its environment (read-only). */\n readonly readOnlyHint?: boolean;\n /** Hint: the tool may perform destructive updates (only meaningful when not read-only). */\n readonly destructiveHint?: boolean;\n /** Hint: repeated calls with the same arguments have no additional effect. */\n readonly idempotentHint?: boolean;\n /** Hint: the tool interacts with an open world of external entities. */\n readonly openWorldHint?: boolean;\n}\n\n/**\n * A tool descriptor discovered from an MCP server via {@link listMcpTools}.\n * @public\n */\nexport interface IMcpToolDescriptor {\n /** Tool name (unique within a server). */\n readonly name: string;\n /** Human-readable description, when the server provided one. */\n readonly description: string | undefined;\n /**\n * The tool's declared input schema as raw JSON. Per the MCP spec this is normally a JSON\n * Schema object; carried verbatim so {@link adaptMcpTools} can run it through\n * `JsonSchema.fromJson` (and surface it on {@link IMcpSkippedTool} when it is outside the\n * supported subset).\n */\n readonly inputSchema: JsonValue;\n /**\n * The tool's normalized behavior annotations, when the server provided any usable ones.\n * Absent when the server declared no annotations (or only malformed/unknown fields).\n * See {@link IMcpToolAnnotations}.\n */\n readonly annotations?: IMcpToolAnnotations;\n}\n\n/**\n * Successful projection of an MCP `CallToolResult` produced by {@link callMcpTool}.\n *\n * @remarks\n * `content` is the text concatenation of the result's `text` blocks; non-text blocks\n * (image / audio / resource) are projected to a one-line `[<type> block]` summary\n * (multimodal passthrough is out of scope at v0.1). A result with `isError: true` is mapped\n * to `Result.fail(content)` rather than returned here, so it is never silently swallowed.\n *\n * @public\n */\nexport interface IMcpToolCallResult {\n /** The projected text content of the tool result. */\n readonly content: string;\n}\n\n// ============================================================================\n// Adapter (Constraint 1)\n// ============================================================================\n\n/**\n * A tool that was discovered but could NOT be adapted into an `AiAssist.IAiClientTool`,\n * because its `inputSchema` is outside the JSON Schema subset supported by\n * `JsonSchema.fromJson`. Surfaced structurally so callers/the probe can enumerate exactly which\n * subset features a server needs (with the raw schema in hand to extend `fromJson` later).\n * @public\n */\nexport interface IMcpSkippedTool {\n /** The tool's name. */\n readonly name: string;\n /** Why the tool was skipped — the JSON-pointer reason from `JsonSchema.fromJson`, or a structural reason. */\n readonly reason: string;\n /** The raw failing input schema, verbatim, in hand for additively widening `JsonSchema.fromJson`. */\n readonly schema: JsonValue;\n}\n\n/**\n * Options for {@link adaptMcpTools}.\n * @public\n */\nexport interface IAdaptMcpToolsOptions {\n /**\n * Logger for the NOISY per-tool skip warnings. When a tool is skipped, a `warning` is emitted\n * including the tool name, the JSON-pointer reason, and the raw failing schema. When omitted,\n * skips are still surfaced structurally on {@link IAdaptMcpToolsResult.skipped}.\n */\n readonly logger?: Logging.ILogger;\n}\n\n/**\n * The result of {@link adaptMcpTools}: cleanly-adapted client tools plus the structurally-surfaced\n * set of tools that could not be adapted (graceful degradation, Constraint 1).\n * @public\n */\nexport interface IAdaptMcpToolsResult {\n /** Tools adapted into `IAiClientTool` — safe to hand to `AiAssist.executeClientToolTurn`. */\n readonly tools: ReadonlyArray<AiAssist.IAiClientTool>;\n /** Tools excluded because their `inputSchema` is outside the supported JSON Schema subset. */\n readonly skipped: ReadonlyArray<IMcpSkippedTool>;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../../../src/packlets/mcp/operations.ts"],"names":[],"mappings":"AAsBA;;;;GAIG;AAEH,OAAO,
|
|
1
|
+
{"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../../../src/packlets/mcp/operations.ts"],"names":[],"mappings":"AAsBA;;;;GAIG;AAEH,OAAO,EAAiC,KAAK,MAAM,EAAqC,MAAM,eAAe,CAAC;AAC9G,OAAO,EAAc,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEhE,OAAO,EACL,KAAK,WAAW,EAEhB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACxB,MAAM,SAAS,CAAC;AAsEjB;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAyB3G;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,WAAW,EACpB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,UAAU,GACf,OAAO,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAkBrC"}
|
|
@@ -31,17 +31,42 @@ exports.callMcpTool = callMcpTool;
|
|
|
31
31
|
const ts_utils_1 = require("@fgv/ts-utils");
|
|
32
32
|
const ts_json_base_1 = require("@fgv/ts-json-base");
|
|
33
33
|
const session_1 = require("./session");
|
|
34
|
+
/**
|
|
35
|
+
* Validates/normalizes a raw (untrusted) MCP `Tool.annotations` blob into an
|
|
36
|
+
* {@link IMcpToolAnnotations}, keeping only the five known fields that convert cleanly.
|
|
37
|
+
*
|
|
38
|
+
* @remarks
|
|
39
|
+
* Each known field is converted independently with its own Converter, so a present-but-malformed
|
|
40
|
+
* field is dropped (never failing the whole blob) and unknown keys are ignored. Returns
|
|
41
|
+
* `undefined` when the blob is absent, not a JSON object, or normalizes to no usable known
|
|
42
|
+
* fields — so a tool with no (usable) annotations leaves {@link IMcpToolDescriptor.annotations}
|
|
43
|
+
* absent. The raw server value is never propagated verbatim (per the MCP untrusted-server
|
|
44
|
+
* warning).
|
|
45
|
+
*/
|
|
46
|
+
function _normalizeAnnotations(raw) {
|
|
47
|
+
const objResult = ts_json_base_1.Converters.jsonObject.convert(raw);
|
|
48
|
+
if (objResult.isFailure()) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
const obj = objResult.value;
|
|
52
|
+
const title = ts_utils_1.Converters.string.convert(obj.title).orDefault();
|
|
53
|
+
const readOnlyHint = ts_utils_1.Converters.boolean.convert(obj.readOnlyHint).orDefault();
|
|
54
|
+
const destructiveHint = ts_utils_1.Converters.boolean.convert(obj.destructiveHint).orDefault();
|
|
55
|
+
const idempotentHint = ts_utils_1.Converters.boolean.convert(obj.idempotentHint).orDefault();
|
|
56
|
+
const openWorldHint = ts_utils_1.Converters.boolean.convert(obj.openWorldHint).orDefault();
|
|
57
|
+
const normalized = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (title !== undefined ? { title } : {})), (readOnlyHint !== undefined ? { readOnlyHint } : {})), (destructiveHint !== undefined ? { destructiveHint } : {})), (idempotentHint !== undefined ? { idempotentHint } : {})), (openWorldHint !== undefined ? { openWorldHint } : {}));
|
|
58
|
+
return Object.keys(normalized).length > 0 ? normalized : undefined;
|
|
59
|
+
}
|
|
34
60
|
/**
|
|
35
61
|
* Projects a single SDK tool descriptor into a public {@link IMcpToolDescriptor}. The
|
|
36
62
|
* `inputSchema` field is validated as a `JsonValue`; an absent/non-JSON schema becomes `null`
|
|
37
63
|
* (which {@link adaptMcpTools} then reports as un-adaptable rather than offering it to the model).
|
|
64
|
+
* The raw `annotations` blob is validated/normalized (never propagated raw) per the MCP
|
|
65
|
+
* untrusted-server warning.
|
|
38
66
|
*/
|
|
39
67
|
function _toDescriptor(tool) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
description: tool.description,
|
|
43
|
-
inputSchema: ts_json_base_1.Converters.jsonValue.convert(tool.inputSchema).orDefault(null)
|
|
44
|
-
};
|
|
68
|
+
const annotations = _normalizeAnnotations(tool.annotations);
|
|
69
|
+
return Object.assign({ name: tool.name, description: tool.description, inputSchema: ts_json_base_1.Converters.jsonValue.convert(tool.inputSchema).orDefault(null) }, (annotations !== undefined ? { annotations } : {}));
|
|
45
70
|
}
|
|
46
71
|
/**
|
|
47
72
|
* Projects the SDK `CallToolResult` content blocks to a single string: `text` blocks are
|
|
@@ -1 +1 @@
|
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CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;SAC5F,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,IAAI,MAAM,GAAG,EAAE,CAAC;SACzD,SAAS,CAAC,CAAC,GAAG,EAA8B,EAAE;QAC7C,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC7C,IAAI,GAAG,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;YACzB,OAAO,IAAA,eAAI,EAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,IAAI,qBAAqB,CAAC,CAAC;QACjF,CAAC;QACD,OAAO,IAAA,kBAAO,EAAC,EAAE,OAAO,EAAE,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Tool discovery (`listMcpTools`, paginated) and invocation (`callMcpTool`, with `CallToolResult`\n * projection), converting the throwing SDK calls into `Result<T>`.\n * @packageDocumentation\n */\n\nimport { type Result, captureAsyncResult, fail, succeed } from '@fgv/ts-utils';\nimport { Converters, type JsonObject } from '@fgv/ts-json-base';\n\nimport { type IMcpSession, type IMcpToolCallResult, type IMcpToolDescriptor } from './model';\nimport { type ISdkContentBlock, type ISdkToolDescriptor } from './sdk';\nimport { McpSession } from './session';\n\n/**\n * Projects a single SDK tool descriptor into a public {@link IMcpToolDescriptor}. The\n * `inputSchema` field is validated as a `JsonValue`; an absent/non-JSON schema becomes `null`\n * (which {@link adaptMcpTools} then reports as un-adaptable rather than offering it to the model).\n */\nfunction _toDescriptor(tool: ISdkToolDescriptor): IMcpToolDescriptor {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: Converters.jsonValue.convert(tool.inputSchema).orDefault(null)\n };\n}\n\n/**\n * Projects the SDK `CallToolResult` content blocks to a single string: `text` blocks are\n * concatenated; every other block type becomes a one-line `[<type> block]` summary.\n */\nfunction _projectContent(blocks: ReadonlyArray<ISdkContentBlock> | undefined): string {\n if (blocks === undefined || blocks.length === 0) {\n return '';\n }\n return blocks\n .map((block) =>\n block.type === 'text' && block.text !== undefined ? block.text : `[${block.type} block]`\n )\n .join('\\n');\n}\n\n/**\n * Lists every tool a connected MCP server advertises, following the SDK's `nextCursor`\n * pagination until the full catalog is accumulated.\n *\n * @param session - A session from `connectMcpSession`.\n * @returns `Success` with the full tool catalog, or `Failure` on a foreign handle or a\n * transport/protocol error.\n * @public\n */\nexport async function listMcpTools(session: IMcpSession): Promise<Result<ReadonlyArray<IMcpToolDescriptor>>> {\n const sessionResult = McpSession.fromHandle(session);\n if (sessionResult.isFailure()) {\n return fail(`listMcpTools: ${sessionResult.message}`);\n }\n const { client } = sessionResult.value;\n\n const all: IMcpToolDescriptor[] = [];\n let cursor: string | undefined;\n\n // Cursor-paginated loop: fetch each page, accumulate, advance until nextCursor is absent.\n do {\n const pageResult = await captureAsyncResult(() =>\n client.listTools(cursor !== undefined ? { cursor } : undefined)\n ).withErrorFormat((msg) => `listMcpTools: ${msg}`);\n if (pageResult.isFailure()) {\n return fail(pageResult.message);\n }\n for (const tool of pageResult.value.tools) {\n all.push(_toDescriptor(tool));\n }\n cursor = pageResult.value.nextCursor;\n } while (cursor !== undefined);\n\n return succeed(all);\n}\n\n/**\n * Calls a named tool on a connected MCP server.\n *\n * @remarks\n * The SDK `CallToolResult` is projected to {@link IMcpToolCallResult} (text-block concatenation;\n * non-text blocks summarized). A result flagged `isError: true` is mapped to `Result.fail` with\n * the projected content — it is never swallowed, so `executeClientToolTurn` routes it back to the\n * model as a provider-native error tool-result.\n *\n * @param session - A session from `connectMcpSession`.\n * @param name - The tool name to invoke.\n * @param args - The tool arguments (a JSON object).\n * @returns `Success` with the projected content, or `Failure` on tool error / transport error /\n * foreign handle.\n * @public\n */\nexport async function callMcpTool(\n session: IMcpSession,\n name: string,\n args: JsonObject\n): Promise<Result<IMcpToolCallResult>> {\n const sessionResult = McpSession.fromHandle(session);\n if (sessionResult.isFailure()) {\n return fail(`callMcpTool: ${sessionResult.message}`);\n }\n // The `withErrorFormat` wraps only transport/throw failures (it transforms the failure flowing\n // out of `captureAsyncResult`); the `isError` failure created in the later `onSuccess` is\n // downstream and stays clean, so the model-facing tool-error text is the server's verbatim\n // content rather than a doubly-prefixed message.\n return captureAsyncResult(() => sessionResult.value.client.callTool({ name, arguments: args }))\n .withErrorFormat((msg) => `callMcpTool '${name}': ${msg}`)\n .onSuccess((raw): Result<IMcpToolCallResult> => {\n const content = _projectContent(raw.content);\n if (raw.isError === true) {\n return fail(content.length > 0 ? content : `tool '${name}' reported an error`);\n }\n return succeed({ content });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"operations.js","sourceRoot":"","sources":["../../../src/packlets/mcp/operations.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;AA+F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AS,EAAE,EAAE,CAAC;QAC9B,OAAO,IAAA,eAAI,EAAC,gBAAgB,aAAa,CAAC,OAAO,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,+FAA+F;IAC/F,0FAA0F;IAC1F,2FAA2F;IAC3F,iDAAiD;IACjD,OAAO,IAAA,6BAAkB,EAAC,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;SAC5F,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,IAAI,MAAM,GAAG,EAAE,CAAC;SACzD,SAAS,CAAC,CAAC,GAAG,EAA8B,EAAE;QAC7C,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC7C,IAAI,GAAG,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;YACzB,OAAO,IAAA,eAAI,EAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,IAAI,qBAAqB,CAAC,CAAC;QACjF,CAAC;QACD,OAAO,IAAA,kBAAO,EAAC,EAAE,OAAO,EAAE,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Tool discovery (`listMcpTools`, paginated) and invocation (`callMcpTool`, with `CallToolResult`\n * projection), converting the throwing SDK calls into `Result<T>`.\n * @packageDocumentation\n */\n\nimport { Converters as UtilsConverters, type Result, captureAsyncResult, fail, succeed } from '@fgv/ts-utils';\nimport { Converters, type JsonObject } from '@fgv/ts-json-base';\n\nimport {\n type IMcpSession,\n type IMcpToolAnnotations,\n type IMcpToolCallResult,\n type IMcpToolDescriptor\n} from './model';\nimport { type ISdkContentBlock, type ISdkToolDescriptor } from './sdk';\nimport { McpSession } from './session';\n\n/**\n * Validates/normalizes a raw (untrusted) MCP `Tool.annotations` blob into an\n * {@link IMcpToolAnnotations}, keeping only the five known fields that convert cleanly.\n *\n * @remarks\n * Each known field is converted independently with its own Converter, so a present-but-malformed\n * field is dropped (never failing the whole blob) and unknown keys are ignored. Returns\n * `undefined` when the blob is absent, not a JSON object, or normalizes to no usable known\n * fields — so a tool with no (usable) annotations leaves {@link IMcpToolDescriptor.annotations}\n * absent. The raw server value is never propagated verbatim (per the MCP untrusted-server\n * warning).\n */\nfunction _normalizeAnnotations(raw: unknown): IMcpToolAnnotations | undefined {\n const objResult = Converters.jsonObject.convert(raw);\n if (objResult.isFailure()) {\n return undefined;\n }\n const obj = objResult.value;\n const title = UtilsConverters.string.convert(obj.title).orDefault();\n const readOnlyHint = UtilsConverters.boolean.convert(obj.readOnlyHint).orDefault();\n const destructiveHint = UtilsConverters.boolean.convert(obj.destructiveHint).orDefault();\n const idempotentHint = UtilsConverters.boolean.convert(obj.idempotentHint).orDefault();\n const openWorldHint = UtilsConverters.boolean.convert(obj.openWorldHint).orDefault();\n\n const normalized: IMcpToolAnnotations = {\n ...(title !== undefined ? { title } : {}),\n ...(readOnlyHint !== undefined ? { readOnlyHint } : {}),\n ...(destructiveHint !== undefined ? { destructiveHint } : {}),\n ...(idempotentHint !== undefined ? { idempotentHint } : {}),\n ...(openWorldHint !== undefined ? { openWorldHint } : {})\n };\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\n/**\n * Projects a single SDK tool descriptor into a public {@link IMcpToolDescriptor}. The\n * `inputSchema` field is validated as a `JsonValue`; an absent/non-JSON schema becomes `null`\n * (which {@link adaptMcpTools} then reports as un-adaptable rather than offering it to the model).\n * The raw `annotations` blob is validated/normalized (never propagated raw) per the MCP\n * untrusted-server warning.\n */\nfunction _toDescriptor(tool: ISdkToolDescriptor): IMcpToolDescriptor {\n const annotations = _normalizeAnnotations(tool.annotations);\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: Converters.jsonValue.convert(tool.inputSchema).orDefault(null),\n ...(annotations !== undefined ? { annotations } : {})\n };\n}\n\n/**\n * Projects the SDK `CallToolResult` content blocks to a single string: `text` blocks are\n * concatenated; every other block type becomes a one-line `[<type> block]` summary.\n */\nfunction _projectContent(blocks: ReadonlyArray<ISdkContentBlock> | undefined): string {\n if (blocks === undefined || blocks.length === 0) {\n return '';\n }\n return blocks\n .map((block) =>\n block.type === 'text' && block.text !== undefined ? block.text : `[${block.type} block]`\n )\n .join('\\n');\n}\n\n/**\n * Lists every tool a connected MCP server advertises, following the SDK's `nextCursor`\n * pagination until the full catalog is accumulated.\n *\n * @param session - A session from `connectMcpSession`.\n * @returns `Success` with the full tool catalog, or `Failure` on a foreign handle or a\n * transport/protocol error.\n * @public\n */\nexport async function listMcpTools(session: IMcpSession): Promise<Result<ReadonlyArray<IMcpToolDescriptor>>> {\n const sessionResult = McpSession.fromHandle(session);\n if (sessionResult.isFailure()) {\n return fail(`listMcpTools: ${sessionResult.message}`);\n }\n const { client } = sessionResult.value;\n\n const all: IMcpToolDescriptor[] = [];\n let cursor: string | undefined;\n\n // Cursor-paginated loop: fetch each page, accumulate, advance until nextCursor is absent.\n do {\n const pageResult = await captureAsyncResult(() =>\n client.listTools(cursor !== undefined ? { cursor } : undefined)\n ).withErrorFormat((msg) => `listMcpTools: ${msg}`);\n if (pageResult.isFailure()) {\n return fail(pageResult.message);\n }\n for (const tool of pageResult.value.tools) {\n all.push(_toDescriptor(tool));\n }\n cursor = pageResult.value.nextCursor;\n } while (cursor !== undefined);\n\n return succeed(all);\n}\n\n/**\n * Calls a named tool on a connected MCP server.\n *\n * @remarks\n * The SDK `CallToolResult` is projected to {@link IMcpToolCallResult} (text-block concatenation;\n * non-text blocks summarized). A result flagged `isError: true` is mapped to `Result.fail` with\n * the projected content — it is never swallowed, so `executeClientToolTurn` routes it back to the\n * model as a provider-native error tool-result.\n *\n * @param session - A session from `connectMcpSession`.\n * @param name - The tool name to invoke.\n * @param args - The tool arguments (a JSON object).\n * @returns `Success` with the projected content, or `Failure` on tool error / transport error /\n * foreign handle.\n * @public\n */\nexport async function callMcpTool(\n session: IMcpSession,\n name: string,\n args: JsonObject\n): Promise<Result<IMcpToolCallResult>> {\n const sessionResult = McpSession.fromHandle(session);\n if (sessionResult.isFailure()) {\n return fail(`callMcpTool: ${sessionResult.message}`);\n }\n // The `withErrorFormat` wraps only transport/throw failures (it transforms the failure flowing\n // out of `captureAsyncResult`); the `isError` failure created in the later `onSuccess` is\n // downstream and stays clean, so the model-facing tool-error text is the server's verbatim\n // content rather than a doubly-prefixed message.\n return captureAsyncResult(() => sessionResult.value.client.callTool({ name, arguments: args }))\n .withErrorFormat((msg) => `callMcpTool '${name}': ${msg}`)\n .onSuccess((raw): Result<IMcpToolCallResult> => {\n const content = _projectContent(raw.content);\n if (raw.isError === true) {\n return fail(content.length > 0 ? content : `tool '${name}' reported an error`);\n }\n return succeed({ content });\n });\n}\n"]}
|
|
@@ -29,6 +29,12 @@ export interface ISdkToolDescriptor {
|
|
|
29
29
|
readonly name: string;
|
|
30
30
|
readonly description?: string;
|
|
31
31
|
readonly inputSchema?: unknown;
|
|
32
|
+
/**
|
|
33
|
+
* Raw MCP `Tool.annotations` (untrusted). Declared as `unknown` so the SDK field survives
|
|
34
|
+
* narrowing; the operations layer validates/normalizes it (never propagates raw) per the MCP
|
|
35
|
+
* spec's untrusted-server warning.
|
|
36
|
+
*/
|
|
37
|
+
readonly annotations?: unknown;
|
|
32
38
|
}
|
|
33
39
|
/**
|
|
34
40
|
* Projection of the SDK's `ListToolsResult` (one page).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../../src/packlets/mcp/sdk.ts"],"names":[],"mappings":"AAwCA;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC;AAEnC;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAAC;IACnD,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC;IAClD,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,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MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACrG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACtC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,UAAU,CAEpE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,GAAG,aAAa,CAOzE;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,aAAa,CAI3F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../../src/packlets/mcp/sdk.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;
|
|
1
|
+
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../../src/packlets/mcp/sdk.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;AA4GH,gCAEC;AAMD,gDAOC;AAMD,8CAIC;AAnID;;;;;;;;;;;;GAYG;AAEH,wEAAmE;AACnE,wEAAiF;AACjF,0FAAmG;AAqFnG;;;;GAIG;AACH,SAAgB,UAAU,CAAC,IAAY,EAAE,OAAe;IACtD,OAAO,IAAI,iBAAM,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE,CAA0B,CAAC;AACtF,CAAC;AAED;;;GAGG;AACH,SAAgB,kBAAkB,CAAC,MAAuB;IACxD,OAAO,IAAI,+BAAoB,CAAC;QAC9B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;QAChD,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,GAAG,EAAE,MAAM,CAAC,GAAG;KAChB,CAA6B,CAAC;AACjC,CAAC;AAED;;;GAGG;AACH,SAAgB,iBAAiB,CAAC,GAAQ,EAAE,OAAgC;IAC1E,OAAO,IAAI,iDAA6B,CAAC,GAAG,EAAE;QAC5C,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,SAAS;KAC/C,CAA6B,CAAC;AACjC,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * **The single `@modelcontextprotocol/sdk` import site for the entire package.**\n *\n * Every other module in `@fgv/ts-extras-mcp` depends only on the minimal local projection\n * exported here (`ISdkClient`, `ISdkTransport`, the three `make*` factories) — never on the SDK\n * directly. This keeps the announced v2 client-package rename a one-file change and lets unit\n * tests mock this module instead of the SDK internals (no live server required).\n *\n * The only `as unknown as` casts in the package live here, at the boundary where the real SDK\n * objects are narrowed to the local projection.\n *\n * @internal\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\n\n/**\n * Opaque transport handle. The concrete value is an SDK `Transport`; consumers of this module\n * treat it as opaque and only ever hand it back to {@link makeClient}-produced clients.\n * @internal\n */\nexport type ISdkTransport = object;\n\n/**\n * A single content block in an MCP `CallToolResult`. Only `text` blocks carry inline content;\n * all other block types are projected to a structural summary by the operations layer.\n * @internal\n */\nexport interface ISdkContentBlock {\n readonly type: string;\n readonly text?: string;\n}\n\n/**\n * Projection of the SDK's `CallToolResult`.\n * @internal\n */\nexport interface ISdkCallToolResult {\n readonly content?: ReadonlyArray<ISdkContentBlock>;\n readonly isError?: boolean;\n}\n\n/**\n * Projection of a single tool descriptor in the SDK's `ListToolsResult`.\n * @internal\n */\nexport interface ISdkToolDescriptor {\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: unknown;\n /**\n * Raw MCP `Tool.annotations` (untrusted). Declared as `unknown` so the SDK field survives\n * narrowing; the operations layer validates/normalizes it (never propagates raw) per the MCP\n * spec's untrusted-server warning.\n */\n readonly annotations?: unknown;\n}\n\n/**\n * Projection of the SDK's `ListToolsResult` (one page).\n * @internal\n */\nexport interface ISdkListToolsResult {\n readonly tools: ReadonlyArray<ISdkToolDescriptor>;\n readonly nextCursor?: string;\n}\n\n/**\n * Server identity returned by the SDK's `getServerVersion()` after the initialize handshake.\n * @internal\n */\nexport interface ISdkImplementation {\n readonly name: string;\n readonly version: string;\n}\n\n/**\n * Minimal projection of the SDK `Client` surface the package depends on.\n * @internal\n */\nexport interface ISdkClient {\n connect(transport: ISdkTransport): Promise<void>;\n getServerVersion(): ISdkImplementation | undefined;\n listTools(params?: { cursor?: string }): Promise<ISdkListToolsResult>;\n callTool(params: { name: string; arguments?: Record<string, unknown> }): Promise<ISdkCallToolResult>;\n close(): Promise<void>;\n}\n\n/**\n * Parameters for the stdio transport factory.\n * @internal\n */\nexport interface ISdkStdioParams {\n readonly command: string;\n readonly args?: ReadonlyArray<string>;\n readonly env?: Record<string, string>;\n readonly cwd?: string;\n}\n\n/**\n * Constructs an MCP client. The `as unknown as` cast is the package's single SDK-type\n * bridge — the runtime object is a real SDK `Client`.\n * @internal\n */\nexport function makeClient(name: string, version: string): ISdkClient {\n return new Client({ name, version }, { capabilities: {} }) as unknown as ISdkClient;\n}\n\n/**\n * Constructs a stdio transport that spawns the given command as a subprocess.\n * @internal\n */\nexport function makeStdioTransport(params: ISdkStdioParams): ISdkTransport {\n return new StdioClientTransport({\n command: params.command,\n args: params.args ? [...params.args] : undefined,\n env: params.env,\n cwd: params.cwd\n }) as unknown as ISdkTransport;\n}\n\n/**\n * Constructs a Streamable-HTTP transport for the given URL, with optional static headers.\n * @internal\n */\nexport function makeHttpTransport(url: URL, headers?: Record<string, string>): ISdkTransport {\n return new StreamableHTTPClientTransport(url, {\n requestInit: headers ? { headers } : undefined\n }) as unknown as ISdkTransport;\n}\n"]}
|
|
@@ -412,5 +412,118 @@ describe('adaptMcpTools', () => {
|
|
|
412
412
|
expect(await execute({ q: 'hello' })).toFailWith(/denied/);
|
|
413
413
|
});
|
|
414
414
|
});
|
|
415
|
+
// ==========================================================================
|
|
416
|
+
// C2 — MCP Tool.annotations passthrough (normalized, never raw)
|
|
417
|
+
// ==========================================================================
|
|
418
|
+
describe('annotations passthrough (C2)', () => {
|
|
419
|
+
const goodSchema2 = { type: 'object', properties: { q: { type: 'string' } }, required: ['q'] };
|
|
420
|
+
test('all five hints round-trip onto descriptor.annotations and config.annotations', async () => {
|
|
421
|
+
const annotations = {
|
|
422
|
+
title: 'Recall Memory',
|
|
423
|
+
readOnlyHint: true,
|
|
424
|
+
destructiveHint: false,
|
|
425
|
+
idempotentHint: true,
|
|
426
|
+
openWorldHint: false
|
|
427
|
+
};
|
|
428
|
+
const fake = makeFakeClient({
|
|
429
|
+
listTools: jest.fn(async () => ({
|
|
430
|
+
tools: [{ name: 'recall', description: 'r', inputSchema: goodSchema2, annotations }]
|
|
431
|
+
}))
|
|
432
|
+
});
|
|
433
|
+
const session = await connectWith(fake);
|
|
434
|
+
expect(await (0, mcp_1.listMcpTools)(session)).toSucceedAndSatisfy((tools) => {
|
|
435
|
+
expect(tools[0].annotations).toEqual(annotations);
|
|
436
|
+
});
|
|
437
|
+
const session2 = await connectWith(makeFakeClient({
|
|
438
|
+
listTools: jest.fn(async () => ({
|
|
439
|
+
tools: [{ name: 'recall', description: 'r', inputSchema: goodSchema2, annotations }]
|
|
440
|
+
}))
|
|
441
|
+
}));
|
|
442
|
+
expect(await (0, mcp_1.adaptMcpTools)(session2)).toSucceedAndSatisfy((result) => {
|
|
443
|
+
expect(result.tools[0].config.annotations).toEqual(annotations);
|
|
444
|
+
});
|
|
445
|
+
});
|
|
446
|
+
test('a tool with no annotations leaves the field absent', async () => {
|
|
447
|
+
const fake = makeFakeClient({
|
|
448
|
+
listTools: jest.fn(async () => ({ tools: [{ name: 'plain', inputSchema: goodSchema2 }] }))
|
|
449
|
+
});
|
|
450
|
+
const session = await connectWith(fake);
|
|
451
|
+
expect(await (0, mcp_1.listMcpTools)(session)).toSucceedAndSatisfy((tools) => {
|
|
452
|
+
expect(tools[0]).not.toHaveProperty('annotations');
|
|
453
|
+
});
|
|
454
|
+
const session2 = await connectWith(makeFakeClient({
|
|
455
|
+
listTools: jest.fn(async () => ({ tools: [{ name: 'plain', inputSchema: goodSchema2 }] }))
|
|
456
|
+
}));
|
|
457
|
+
expect(await (0, mcp_1.adaptMcpTools)(session2)).toSucceedAndSatisfy((result) => {
|
|
458
|
+
expect(result.tools[0].config).not.toHaveProperty('annotations');
|
|
459
|
+
});
|
|
460
|
+
});
|
|
461
|
+
test('a malformed annotations blob is normalized (known fields kept, junk dropped), never raw-propagated', async () => {
|
|
462
|
+
// readOnlyHint is the wrong type (dropped); bogusField is unknown (dropped); title is valid (kept).
|
|
463
|
+
const rawAnnotations = {
|
|
464
|
+
title: 'Keep Me',
|
|
465
|
+
readOnlyHint: 'yes-please',
|
|
466
|
+
destructiveHint: true,
|
|
467
|
+
bogusField: { nested: 42 }
|
|
468
|
+
};
|
|
469
|
+
const fake = makeFakeClient({
|
|
470
|
+
listTools: jest.fn(async () => ({
|
|
471
|
+
tools: [{ name: 'messy', inputSchema: goodSchema2, annotations: rawAnnotations }]
|
|
472
|
+
}))
|
|
473
|
+
});
|
|
474
|
+
const session = await connectWith(fake);
|
|
475
|
+
expect(await (0, mcp_1.listMcpTools)(session)).toSucceedAndSatisfy((tools) => {
|
|
476
|
+
// Only the well-typed known fields survive; the malformed readOnlyHint and unknown
|
|
477
|
+
// bogusField are dropped; the raw blob is never propagated.
|
|
478
|
+
expect(tools[0].annotations).toEqual({ title: 'Keep Me', destructiveHint: true });
|
|
479
|
+
expect(tools[0].annotations).not.toHaveProperty('readOnlyHint');
|
|
480
|
+
expect(tools[0].annotations).not.toHaveProperty('bogusField');
|
|
481
|
+
});
|
|
482
|
+
});
|
|
483
|
+
test('an all-junk annotations blob normalizes to an absent field (not an empty object)', async () => {
|
|
484
|
+
const fake = makeFakeClient({
|
|
485
|
+
listTools: jest.fn(async () => ({
|
|
486
|
+
tools: [
|
|
487
|
+
{ name: 'junk', inputSchema: goodSchema2, annotations: { unknownOnly: 1, readOnlyHint: 3 } }
|
|
488
|
+
]
|
|
489
|
+
}))
|
|
490
|
+
});
|
|
491
|
+
const session = await connectWith(fake);
|
|
492
|
+
expect(await (0, mcp_1.listMcpTools)(session)).toSucceedAndSatisfy((tools) => {
|
|
493
|
+
expect(tools[0]).not.toHaveProperty('annotations');
|
|
494
|
+
});
|
|
495
|
+
});
|
|
496
|
+
test('a non-object annotations value is dropped', async () => {
|
|
497
|
+
const fake = makeFakeClient({
|
|
498
|
+
listTools: jest.fn(async () => ({
|
|
499
|
+
tools: [{ name: 'weird', inputSchema: goodSchema2, annotations: 'not-an-object' }]
|
|
500
|
+
}))
|
|
501
|
+
});
|
|
502
|
+
const session = await connectWith(fake);
|
|
503
|
+
expect(await (0, mcp_1.listMcpTools)(session)).toSucceedAndSatisfy((tools) => {
|
|
504
|
+
expect(tools[0]).not.toHaveProperty('annotations');
|
|
505
|
+
});
|
|
506
|
+
});
|
|
507
|
+
test('the skipped-tool path is unaffected by annotations', async () => {
|
|
508
|
+
// A tool with annotations but an unsupported inputSchema is still skipped; annotations do
|
|
509
|
+
// not rescue it or leak onto the skip record.
|
|
510
|
+
const forbidden = {
|
|
511
|
+
type: 'object',
|
|
512
|
+
properties: { name: { type: 'string', pattern: '^a' } }
|
|
513
|
+
};
|
|
514
|
+
const fake = makeFakeClient({
|
|
515
|
+
listTools: jest.fn(async () => ({
|
|
516
|
+
tools: [{ name: 'blocked', inputSchema: forbidden, annotations: { destructiveHint: true } }]
|
|
517
|
+
}))
|
|
518
|
+
});
|
|
519
|
+
const session = await connectWith(fake);
|
|
520
|
+
expect(await (0, mcp_1.adaptMcpTools)(session)).toSucceedAndSatisfy((result) => {
|
|
521
|
+
expect(result.tools).toHaveLength(0);
|
|
522
|
+
expect(result.skipped).toHaveLength(1);
|
|
523
|
+
expect(result.skipped[0].name).toBe('blocked');
|
|
524
|
+
expect(result.skipped[0]).not.toHaveProperty('annotations');
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
});
|
|
415
528
|
});
|
|
416
529
|
//# sourceMappingURL=mcp.test.js.map
|