@fgv/ts-extras-mcp 5.1.0-34
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/5d207610a84e494acaefe7ed13447cda74ddf7da.tar.log +90 -0
- package/.rush/temp/chunked-rush-logs/ts-extras-mcp.build.chunks.jsonl +9 -0
- package/.rush/temp/operation/build/all.log +9 -0
- package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
- package/.rush/temp/operation/build/state.json +3 -0
- package/.rush/temp/shrinkwrap-deps.json +734 -0
- package/CHANGELOG.json +4 -0
- package/README.md +133 -0
- package/config/api-extractor.json +38 -0
- package/config/jest.config.json +13 -0
- package/config/rig.json +6 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/dist/packlets/mcp/adapter.js +122 -0
- package/dist/packlets/mcp/adapter.js.map +1 -0
- package/dist/packlets/mcp/index.js +33 -0
- package/dist/packlets/mcp/index.js.map +1 -0
- package/dist/packlets/mcp/model.js +23 -0
- package/dist/packlets/mcp/model.js.map +1 -0
- package/dist/packlets/mcp/operations.js +119 -0
- package/dist/packlets/mcp/operations.js.map +1 -0
- package/dist/packlets/mcp/sdk.js +67 -0
- package/dist/packlets/mcp/sdk.js.map +1 -0
- package/dist/packlets/mcp/session.js +109 -0
- package/dist/packlets/mcp/session.js.map +1 -0
- package/dist/packlets/mcp/transports.js +96 -0
- package/dist/packlets/mcp/transports.js.map +1 -0
- package/dist/test/unit/endToEnd.test.js +220 -0
- package/dist/test/unit/endToEnd.test.js.map +1 -0
- package/dist/test/unit/index.test.js +41 -0
- package/dist/test/unit/index.test.js.map +1 -0
- package/dist/test/unit/mcp.test.js +381 -0
- package/dist/test/unit/mcp.test.js.map +1 -0
- package/dist/test/unit/sdk.test.js +68 -0
- package/dist/test/unit/sdk.test.js.map +1 -0
- package/dist/ts-extras-mcp.d.ts +290 -0
- package/dist/tsdoc-metadata.json +11 -0
- package/eslint.config.js +15 -0
- package/etc/ts-extras-mcp.api.md +104 -0
- package/lib/index.d.ts +28 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +65 -0
- package/lib/index.js.map +1 -0
- package/lib/packlets/mcp/adapter.d.ts +33 -0
- package/lib/packlets/mcp/adapter.d.ts.map +1 -0
- package/lib/packlets/mcp/adapter.js +125 -0
- package/lib/packlets/mcp/adapter.js.map +1 -0
- package/lib/packlets/mcp/index.d.ts +10 -0
- package/lib/packlets/mcp/index.d.ts.map +1 -0
- package/lib/packlets/mcp/index.js +57 -0
- package/lib/packlets/mcp/index.js.map +1 -0
- package/lib/packlets/mcp/model.d.ts +155 -0
- package/lib/packlets/mcp/model.d.ts.map +1 -0
- package/lib/packlets/mcp/model.js +24 -0
- package/lib/packlets/mcp/model.js.map +1 -0
- package/lib/packlets/mcp/operations.d.ts +36 -0
- package/lib/packlets/mcp/operations.d.ts.map +1 -0
- package/lib/packlets/mcp/operations.js +123 -0
- package/lib/packlets/mcp/operations.js.map +1 -0
- package/lib/packlets/mcp/sdk.d.ts +91 -0
- package/lib/packlets/mcp/sdk.d.ts.map +1 -0
- package/lib/packlets/mcp/sdk.js +72 -0
- package/lib/packlets/mcp/sdk.js.map +1 -0
- package/lib/packlets/mcp/session.d.ts +43 -0
- package/lib/packlets/mcp/session.d.ts.map +1 -0
- package/lib/packlets/mcp/session.js +115 -0
- package/lib/packlets/mcp/session.js.map +1 -0
- package/lib/packlets/mcp/transports.d.ts +49 -0
- package/lib/packlets/mcp/transports.d.ts.map +1 -0
- package/lib/packlets/mcp/transports.js +102 -0
- package/lib/packlets/mcp/transports.js.map +1 -0
- package/lib/test/unit/endToEnd.test.d.ts +13 -0
- package/lib/test/unit/endToEnd.test.d.ts.map +1 -0
- package/lib/test/unit/endToEnd.test.js +222 -0
- package/lib/test/unit/endToEnd.test.js.map +1 -0
- package/lib/test/unit/index.test.d.ts +2 -0
- package/lib/test/unit/index.test.d.ts.map +1 -0
- package/lib/test/unit/index.test.js +76 -0
- package/lib/test/unit/index.test.js.map +1 -0
- package/lib/test/unit/mcp.test.d.ts +2 -0
- package/lib/test/unit/mcp.test.d.ts.map +1 -0
- package/lib/test/unit/mcp.test.js +416 -0
- package/lib/test/unit/mcp.test.js.map +1 -0
- package/lib/test/unit/sdk.test.d.ts +2 -0
- package/lib/test/unit/sdk.test.d.ts.map +1 -0
- package/lib/test/unit/sdk.test.js +70 -0
- package/lib/test/unit/sdk.test.js.map +1 -0
- package/package.json +86 -0
- package/rush-logs/ts-extras-mcp.build.cache.log +3 -0
- package/rush-logs/ts-extras-mcp.build.log +9 -0
- package/src/index.ts +50 -0
- package/src/packlets/mcp/adapter.ts +152 -0
- package/src/packlets/mcp/index.ts +34 -0
- package/src/packlets/mcp/model.ts +204 -0
- package/src/packlets/mcp/operations.ts +138 -0
- package/src/packlets/mcp/sdk.ts +148 -0
- package/src/packlets/mcp/session.ts +137 -0
- package/src/packlets/mcp/transports.ts +111 -0
- package/src/test/unit/endToEnd.test.ts +254 -0
- package/src/test/unit/index.test.ts +43 -0
- package/src/test/unit/mcp.test.ts +473 -0
- package/src/test/unit/sdk.test.ts +73 -0
- package/temp/build/lint/_eslint-5eVG3S6w.json +54 -0
- package/temp/build/typescript/ts_8nwakTlr.json +1 -0
- package/temp/ts-extras-mcp.api.json +1662 -0
- package/temp/ts-extras-mcp.api.md +104 -0
- package/tsconfig.json +12 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* **The single `@modelcontextprotocol/sdk` import site for the entire package.**
|
|
24
|
+
*
|
|
25
|
+
* Every other module in `@fgv/ts-extras-mcp` depends only on the minimal local projection
|
|
26
|
+
* exported here (`ISdkClient`, `ISdkTransport`, the three `make*` factories) — never on the SDK
|
|
27
|
+
* directly. This keeps the announced v2 client-package rename a one-file change and lets unit
|
|
28
|
+
* tests mock this module instead of the SDK internals (no live server required).
|
|
29
|
+
*
|
|
30
|
+
* The only `as unknown as` casts in the package live here, at the boundary where the real SDK
|
|
31
|
+
* objects are narrowed to the local projection.
|
|
32
|
+
*
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
36
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
37
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
38
|
+
/**
|
|
39
|
+
* Constructs an MCP client. The `as unknown as` cast is the package's single SDK-type
|
|
40
|
+
* bridge — the runtime object is a real SDK `Client`.
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
export function makeClient(name, version) {
|
|
44
|
+
return new Client({ name, version }, { capabilities: {} });
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Constructs a stdio transport that spawns the given command as a subprocess.
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
export function makeStdioTransport(params) {
|
|
51
|
+
return new StdioClientTransport({
|
|
52
|
+
command: params.command,
|
|
53
|
+
args: params.args ? [...params.args] : undefined,
|
|
54
|
+
env: params.env,
|
|
55
|
+
cwd: params.cwd
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Constructs a Streamable-HTTP transport for the given URL, with optional static headers.
|
|
60
|
+
* @internal
|
|
61
|
+
*/
|
|
62
|
+
export function makeHttpTransport(url, headers) {
|
|
63
|
+
return new StreamableHTTPClientTransport(url, {
|
|
64
|
+
requestInit: headers ? { headers } : undefined
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=sdk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../../src/packlets/mcp/sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AA+EnG;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,OAAe;IACtD,OAAO,IAAI,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE,CAA0B,CAAC;AACtF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAAuB;IACxD,OAAO,IAAI,oBAAoB,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,MAAM,UAAU,iBAAiB,CAAC,GAAQ,EAAE,OAAgC;IAC1E,OAAO,IAAI,6BAA6B,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\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"]}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Session lifecycle — connect / close, converting the throwing SDK calls into `Result<T>`.
|
|
24
|
+
* @packageDocumentation
|
|
25
|
+
*/
|
|
26
|
+
import { captureAsyncResult, fail, succeed } from '@fgv/ts-utils';
|
|
27
|
+
import { makeClient } from './sdk';
|
|
28
|
+
import { McpTransport } from './transports';
|
|
29
|
+
/** Default client name advertised during the initialize handshake. */
|
|
30
|
+
const DEFAULT_CLIENT_NAME = '@fgv/ts-extras-mcp';
|
|
31
|
+
/**
|
|
32
|
+
* Default client version advertised during the initialize handshake.
|
|
33
|
+
*
|
|
34
|
+
* @remarks
|
|
35
|
+
* Keep in sync with this package's `package.json` version on each release. It is informational
|
|
36
|
+
* only — MCP servers use it for logging/telemetry, not for behavior — so a drift is low-impact,
|
|
37
|
+
* but it should be bumped alongside the lockstep version. (Reading it from `package.json` at
|
|
38
|
+
* runtime is avoided to keep the bundle free of a JSON import / `require` of the manifest.)
|
|
39
|
+
*/
|
|
40
|
+
const DEFAULT_CLIENT_VERSION = '5.1.0';
|
|
41
|
+
/**
|
|
42
|
+
* Concrete session handle. Packlet-internal — carries the live SDK client that the operations
|
|
43
|
+
* layer recovers via {@link McpSession.fromHandle}. Not exported from the package barrel.
|
|
44
|
+
* @internal
|
|
45
|
+
*/
|
|
46
|
+
export class McpSession {
|
|
47
|
+
constructor(client, clientName, clientVersion, serverInfo) {
|
|
48
|
+
this.client = client;
|
|
49
|
+
this.clientName = clientName;
|
|
50
|
+
this.clientVersion = clientVersion;
|
|
51
|
+
this.serverInfo = serverInfo;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Narrows a public {@link IMcpSession} handle back to the concrete {@link McpSession}. Fails
|
|
55
|
+
* loudly when handed a foreign object that did not originate from {@link connectMcpSession}.
|
|
56
|
+
*/
|
|
57
|
+
static fromHandle(handle) {
|
|
58
|
+
if (handle instanceof McpSession) {
|
|
59
|
+
return succeed(handle);
|
|
60
|
+
}
|
|
61
|
+
return fail('invalid MCP session: expected a handle from connectMcpSession');
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Connects to an MCP server over the given transport and performs the initialize handshake.
|
|
66
|
+
*
|
|
67
|
+
* @param params - Transport plus optional client identity and logger.
|
|
68
|
+
* @returns `Success` with an opaque {@link IMcpSession}, or `Failure` if the transport handle is
|
|
69
|
+
* foreign or the connection/handshake fails.
|
|
70
|
+
* @public
|
|
71
|
+
*/
|
|
72
|
+
export async function connectMcpSession(params) {
|
|
73
|
+
const { transport, clientName, clientVersion, logger } = params;
|
|
74
|
+
const transportResult = McpTransport.fromHandle(transport);
|
|
75
|
+
if (transportResult.isFailure()) {
|
|
76
|
+
return fail(`connectMcpSession: ${transportResult.message}`);
|
|
77
|
+
}
|
|
78
|
+
const name = clientName !== null && clientName !== void 0 ? clientName : DEFAULT_CLIENT_NAME;
|
|
79
|
+
const version = clientVersion !== null && clientVersion !== void 0 ? clientVersion : DEFAULT_CLIENT_VERSION;
|
|
80
|
+
const client = makeClient(name, version);
|
|
81
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`mcp: connecting (client ${name}@${version}, transport ${transportResult.value.transportKind})`);
|
|
82
|
+
return captureAsyncResult(() => client.connect(transportResult.value.sdkTransport))
|
|
83
|
+
.onSuccess(() => {
|
|
84
|
+
const raw = client.getServerVersion();
|
|
85
|
+
const serverInfo = raw !== undefined ? { name: raw.name, version: raw.version } : undefined;
|
|
86
|
+
logger === null || logger === void 0 ? void 0 : logger.info(serverInfo !== undefined
|
|
87
|
+
? `mcp: connected to server ${serverInfo.name}@${serverInfo.version}`
|
|
88
|
+
: 'mcp: connected (server did not report identity)');
|
|
89
|
+
return succeed(new McpSession(client, name, version, serverInfo));
|
|
90
|
+
})
|
|
91
|
+
.withErrorFormat((msg) => `connectMcpSession: ${msg}`);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Closes an MCP session, tearing down the transport (and any spawned subprocess).
|
|
95
|
+
*
|
|
96
|
+
* @param session - A session from {@link connectMcpSession}.
|
|
97
|
+
* @returns `Success(true)`, or `Failure` if the handle is foreign or the close call throws.
|
|
98
|
+
* @public
|
|
99
|
+
*/
|
|
100
|
+
export async function closeMcpSession(session) {
|
|
101
|
+
const sessionResult = McpSession.fromHandle(session);
|
|
102
|
+
if (sessionResult.isFailure()) {
|
|
103
|
+
return fail(`closeMcpSession: ${sessionResult.message}`);
|
|
104
|
+
}
|
|
105
|
+
return captureAsyncResult(() => sessionResult.value.client.close())
|
|
106
|
+
.onSuccess(() => succeed(true))
|
|
107
|
+
.withErrorFormat((msg) => `closeMcpSession: ${msg}`);
|
|
108
|
+
}
|
|
109
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/packlets/mcp/session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;GAGG;AAEH,OAAO,EAAe,kBAAkB,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAG/E,OAAO,EAAmB,UAAU,EAAE,MAAM,OAAO,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,sEAAsE;AACtE,MAAM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AAC;SACvC,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oBAAoB,GAAG,EAAE,CAAC,CAAC;AACzD,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 * Session lifecycle — connect / close, converting the throwing SDK calls into `Result<T>`.\n * @packageDocumentation\n */\n\nimport { type Result, captureAsyncResult, fail, succeed } from '@fgv/ts-utils';\n\nimport { type IConnectMcpSessionParams, type IMcpServerInfo, type IMcpSession } from './model';\nimport { type ISdkClient, makeClient } from './sdk';\nimport { McpTransport } from './transports';\n\n/** Default client name advertised during the initialize handshake. */\nconst DEFAULT_CLIENT_NAME: string = '@fgv/ts-extras-mcp';\n/**\n * Default client version advertised during the initialize handshake.\n *\n * @remarks\n * Keep in sync with this package's `package.json` version on each release. It is informational\n * only — MCP servers use it for logging/telemetry, not for behavior — so a drift is low-impact,\n * but it should be bumped alongside the lockstep version. (Reading it from `package.json` at\n * runtime is avoided to keep the bundle free of a JSON import / `require` of the manifest.)\n */\nconst DEFAULT_CLIENT_VERSION: string = '5.1.0';\n\n/**\n * Concrete session handle. Packlet-internal — carries the live SDK client that the operations\n * layer recovers via {@link McpSession.fromHandle}. Not exported from the package barrel.\n * @internal\n */\nexport class McpSession implements IMcpSession {\n public readonly clientName: string;\n public readonly clientVersion: string;\n public readonly serverInfo: IMcpServerInfo | undefined;\n /** The live SDK client. */\n public readonly client: ISdkClient;\n\n public constructor(\n client: ISdkClient,\n clientName: string,\n clientVersion: string,\n serverInfo: IMcpServerInfo | undefined\n ) {\n this.client = client;\n this.clientName = clientName;\n this.clientVersion = clientVersion;\n this.serverInfo = serverInfo;\n }\n\n /**\n * Narrows a public {@link IMcpSession} handle back to the concrete {@link McpSession}. Fails\n * loudly when handed a foreign object that did not originate from {@link connectMcpSession}.\n */\n public static fromHandle(handle: IMcpSession): Result<McpSession> {\n if (handle instanceof McpSession) {\n return succeed(handle);\n }\n return fail('invalid MCP session: expected a handle from connectMcpSession');\n }\n}\n\n/**\n * Connects to an MCP server over the given transport and performs the initialize handshake.\n *\n * @param params - Transport plus optional client identity and logger.\n * @returns `Success` with an opaque {@link IMcpSession}, or `Failure` if the transport handle is\n * foreign or the connection/handshake fails.\n * @public\n */\nexport async function connectMcpSession(params: IConnectMcpSessionParams): Promise<Result<IMcpSession>> {\n const { transport, clientName, clientVersion, logger } = params;\n\n const transportResult = McpTransport.fromHandle(transport);\n if (transportResult.isFailure()) {\n return fail(`connectMcpSession: ${transportResult.message}`);\n }\n\n const name = clientName ?? DEFAULT_CLIENT_NAME;\n const version = clientVersion ?? DEFAULT_CLIENT_VERSION;\n const client = makeClient(name, version);\n\n logger?.info(\n `mcp: connecting (client ${name}@${version}, transport ${transportResult.value.transportKind})`\n );\n\n return captureAsyncResult(() => client.connect(transportResult.value.sdkTransport))\n .onSuccess(() => {\n const raw = client.getServerVersion();\n const serverInfo: IMcpServerInfo | undefined =\n raw !== undefined ? { name: raw.name, version: raw.version } : undefined;\n logger?.info(\n serverInfo !== undefined\n ? `mcp: connected to server ${serverInfo.name}@${serverInfo.version}`\n : 'mcp: connected (server did not report identity)'\n );\n return succeed<IMcpSession>(new McpSession(client, name, version, serverInfo));\n })\n .withErrorFormat((msg) => `connectMcpSession: ${msg}`);\n}\n\n/**\n * Closes an MCP session, tearing down the transport (and any spawned subprocess).\n *\n * @param session - A session from {@link connectMcpSession}.\n * @returns `Success(true)`, or `Failure` if the handle is foreign or the close call throws.\n * @public\n */\nexport async function closeMcpSession(session: IMcpSession): Promise<Result<true>> {\n const sessionResult = McpSession.fromHandle(session);\n if (sessionResult.isFailure()) {\n return fail(`closeMcpSession: ${sessionResult.message}`);\n }\n return captureAsyncResult(() => sessionResult.value.client.close())\n .onSuccess(() => succeed(true as const))\n .withErrorFormat((msg) => `closeMcpSession: ${msg}`);\n}\n"]}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Transport factories — convert the throwing SDK transport constructors into `Result<T>`.
|
|
24
|
+
* @packageDocumentation
|
|
25
|
+
*/
|
|
26
|
+
import { captureResult, fail, succeed } from '@fgv/ts-utils';
|
|
27
|
+
import { makeHttpTransport, makeStdioTransport } from './sdk';
|
|
28
|
+
/**
|
|
29
|
+
* Concrete transport handle. Packlet-internal — carries the SDK transport that
|
|
30
|
+
* {@link McpTransport.fromHandle} recovers inside {@link connectMcpSession}. Not exported from
|
|
31
|
+
* the package barrel, so it does not appear in the public API surface.
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
export class McpTransport {
|
|
35
|
+
constructor(transportKind, sdkTransport) {
|
|
36
|
+
this.transportKind = transportKind;
|
|
37
|
+
this.sdkTransport = sdkTransport;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Narrows a public {@link IMcpTransport} handle back to the concrete {@link McpTransport}.
|
|
41
|
+
* Fails loudly when handed a foreign object that did not originate from one of this
|
|
42
|
+
* package's transport factories.
|
|
43
|
+
*/
|
|
44
|
+
static fromHandle(handle) {
|
|
45
|
+
if (handle instanceof McpTransport) {
|
|
46
|
+
return succeed(handle);
|
|
47
|
+
}
|
|
48
|
+
return fail('invalid MCP transport: expected a handle from createStdioTransport / createHttpTransport');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates a stdio MCP transport that speaks MCP over the stdin/stdout of a spawned subprocess.
|
|
53
|
+
*
|
|
54
|
+
* @remarks
|
|
55
|
+
* **Security — trust boundary.** The transport spawns `params.command` (with `params.args`) as a
|
|
56
|
+
* child process. Never source the command or arguments from untrusted input; treat them with the
|
|
57
|
+
* same care as any shell-out. See the package README's security note.
|
|
58
|
+
*
|
|
59
|
+
* @param params - The command, arguments, environment, and working directory.
|
|
60
|
+
* @returns `Success` with an opaque transport handle, or `Failure` if the SDK constructor throws
|
|
61
|
+
* (e.g. an empty command).
|
|
62
|
+
* @public
|
|
63
|
+
*/
|
|
64
|
+
export function createStdioTransport(params) {
|
|
65
|
+
if (params.command.trim().length === 0) {
|
|
66
|
+
return fail('createStdioTransport: command must be a non-empty string');
|
|
67
|
+
}
|
|
68
|
+
return captureResult(() => makeStdioTransport({
|
|
69
|
+
command: params.command,
|
|
70
|
+
args: params.args,
|
|
71
|
+
env: params.env,
|
|
72
|
+
cwd: params.cwd
|
|
73
|
+
}))
|
|
74
|
+
.onSuccess((sdkTransport) => succeed(new McpTransport('stdio', sdkTransport)))
|
|
75
|
+
.withErrorFormat((msg) => `createStdioTransport: ${msg}`);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Creates a Streamable-HTTP MCP transport for the given endpoint URL.
|
|
79
|
+
*
|
|
80
|
+
* @param params - The endpoint URL and optional static headers.
|
|
81
|
+
* @returns `Success` with an opaque transport handle, or `Failure` if the URL is invalid or the
|
|
82
|
+
* SDK constructor throws.
|
|
83
|
+
* @public
|
|
84
|
+
*/
|
|
85
|
+
export function createHttpTransport(params) {
|
|
86
|
+
return captureResult(() => new URL(params.url))
|
|
87
|
+
.withErrorFormat(() => `invalid url '${params.url}'`)
|
|
88
|
+
.onSuccess((url) => {
|
|
89
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
90
|
+
return fail(`url must use http or https protocol (got '${url.protocol}')`);
|
|
91
|
+
}
|
|
92
|
+
return captureResult(() => makeHttpTransport(url, params.headers)).onSuccess((sdkTransport) => succeed(new McpTransport('http', sdkTransport)));
|
|
93
|
+
})
|
|
94
|
+
.withErrorFormat((msg) => `createHttpTransport: ${msg}`);
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=transports.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transports.js","sourceRoot":"","sources":["../../../src/packlets/mcp/transports.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;GAGG;AAEH,OAAO,EAAe,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAG1E,OAAO,EAAsB,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAElF;;;;;GAKG;AACH,MAAM,OAAO,YAAY;IAKvB,YAAmB,aAA+B,EAAE,YAA2B;QAC7E,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,UAAU,CAAC,MAAqB;QAC5C,IAAI,MAAM,YAAY,YAAY,EAAE,CAAC;YACnC,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;QACzB,CAAC;QACD,OAAO,IAAI,CAAC,0FAA0F,CAAC,CAAC;IAC1G,CAAC;CACF;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAgC;IACnE,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvC,OAAO,IAAI,CAAC,0DAA0D,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,aAAa,CAAC,GAAG,EAAE,CACxB,kBAAkB,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,GAAG,EAAE,MAAM,CAAC,GAAG;KAChB,CAAC,CACH;SACE,SAAS,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,OAAO,CAAgB,IAAI,YAAY,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;SAC5F,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,yBAAyB,GAAG,EAAE,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA+B;IACjE,OAAO,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;SAC5C,eAAe,CAAC,GAAG,EAAE,CAAC,gBAAgB,MAAM,CAAC,GAAG,GAAG,CAAC;SACpD,SAAS,CAAC,CAAC,GAAG,EAAyB,EAAE;QACxC,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC1D,OAAO,IAAI,CAAC,6CAA6C,GAAG,CAAC,QAAQ,IAAI,CAAC,CAAC;QAC7E,CAAC;QACD,OAAO,aAAa,CAAC,GAAG,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,YAAY,EAAE,EAAE,CAC5F,OAAO,CAAgB,IAAI,YAAY,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAC/D,CAAC;IACJ,CAAC,CAAC;SACD,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,wBAAwB,GAAG,EAAE,CAAC,CAAC;AAC7D,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 * Transport factories — convert the throwing SDK transport constructors into `Result<T>`.\n * @packageDocumentation\n */\n\nimport { type Result, captureResult, fail, succeed } from '@fgv/ts-utils';\n\nimport { type IMcpHttpTransportParams, type IMcpStdioTransportParams, type IMcpTransport } from './model';\nimport { type ISdkTransport, makeHttpTransport, makeStdioTransport } from './sdk';\n\n/**\n * Concrete transport handle. Packlet-internal — carries the SDK transport that\n * {@link McpTransport.fromHandle} recovers inside {@link connectMcpSession}. Not exported from\n * the package barrel, so it does not appear in the public API surface.\n * @internal\n */\nexport class McpTransport implements IMcpTransport {\n public readonly transportKind: 'stdio' | 'http';\n /** The wrapped SDK transport. */\n public readonly sdkTransport: ISdkTransport;\n\n public constructor(transportKind: 'stdio' | 'http', sdkTransport: ISdkTransport) {\n this.transportKind = transportKind;\n this.sdkTransport = sdkTransport;\n }\n\n /**\n * Narrows a public {@link IMcpTransport} handle back to the concrete {@link McpTransport}.\n * Fails loudly when handed a foreign object that did not originate from one of this\n * package's transport factories.\n */\n public static fromHandle(handle: IMcpTransport): Result<McpTransport> {\n if (handle instanceof McpTransport) {\n return succeed(handle);\n }\n return fail('invalid MCP transport: expected a handle from createStdioTransport / createHttpTransport');\n }\n}\n\n/**\n * Creates a stdio MCP transport that speaks MCP over the stdin/stdout of a spawned subprocess.\n *\n * @remarks\n * **Security — trust boundary.** The transport spawns `params.command` (with `params.args`) as a\n * child process. Never source the command or arguments from untrusted input; treat them with the\n * same care as any shell-out. See the package README's security note.\n *\n * @param params - The command, arguments, environment, and working directory.\n * @returns `Success` with an opaque transport handle, or `Failure` if the SDK constructor throws\n * (e.g. an empty command).\n * @public\n */\nexport function createStdioTransport(params: IMcpStdioTransportParams): Result<IMcpTransport> {\n if (params.command.trim().length === 0) {\n return fail('createStdioTransport: command must be a non-empty string');\n }\n return captureResult(() =>\n makeStdioTransport({\n command: params.command,\n args: params.args,\n env: params.env,\n cwd: params.cwd\n })\n )\n .onSuccess((sdkTransport) => succeed<IMcpTransport>(new McpTransport('stdio', sdkTransport)))\n .withErrorFormat((msg) => `createStdioTransport: ${msg}`);\n}\n\n/**\n * Creates a Streamable-HTTP MCP transport for the given endpoint URL.\n *\n * @param params - The endpoint URL and optional static headers.\n * @returns `Success` with an opaque transport handle, or `Failure` if the URL is invalid or the\n * SDK constructor throws.\n * @public\n */\nexport function createHttpTransport(params: IMcpHttpTransportParams): Result<IMcpTransport> {\n return captureResult(() => new URL(params.url))\n .withErrorFormat(() => `invalid url '${params.url}'`)\n .onSuccess((url): Result<IMcpTransport> => {\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return fail(`url must use http or https protocol (got '${url.protocol}')`);\n }\n return captureResult(() => makeHttpTransport(url, params.headers)).onSuccess((sdkTransport) =>\n succeed<IMcpTransport>(new McpTransport('http', sdkTransport))\n );\n })\n .withErrorFormat((msg) => `createHttpTransport: ${msg}`);\n}\n"]}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* End-to-end verification against a REAL in-memory MCP server (the SDK's `Server` +
|
|
24
|
+
* `InMemoryTransport.createLinkedPair()`) — NOT a mocked SDK. This is the durable proof that the
|
|
25
|
+
* brief's two load-bearing constraints actually flow through the full stack: the real SDK `Client`,
|
|
26
|
+
* the real initialize handshake, the real `listTools`/`callTool` round-trips, the `sdk.ts`
|
|
27
|
+
* projection casts, and `adaptMcpTools`' `JsonSchema.fromJson` gate. It is the class of gap that
|
|
28
|
+
* 100%-line-coverage of a mocked seam cannot catch (e.g. a projection-shape mismatch in `sdk.ts`).
|
|
29
|
+
*
|
|
30
|
+
* The fixture server advertises a MIX of tools: two adaptable, and one for each JSON Schema feature
|
|
31
|
+
* `JsonSchema.fromJson` rejects ($ref, oneOf, anyOf, pattern, union `type[]`).
|
|
32
|
+
*/
|
|
33
|
+
import '@fgv/ts-utils-jest';
|
|
34
|
+
import { Logging } from '@fgv/ts-utils';
|
|
35
|
+
// Real MCP SDK server side — exercised over an in-process linked transport pair. Subpath imports
|
|
36
|
+
// resolve via the tsconfig `paths` mapping (the same seam the package's sdk.ts uses).
|
|
37
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
38
|
+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
|
|
39
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
40
|
+
import { adaptMcpTools, callMcpTool, closeMcpSession, connectMcpSession, listMcpTools } from '../../packlets/mcp';
|
|
41
|
+
// Internal: the opaque-handle class. The package exposes only stdio/http transport factories, so a
|
|
42
|
+
// real in-process e2e (which must inject the SDK's InMemoryTransport) wraps it here. Tests may
|
|
43
|
+
// import internal modules directly (TESTING_GUIDELINES § Testing Internal Code).
|
|
44
|
+
// eslint-disable-next-line @rushstack/packlets/mechanics
|
|
45
|
+
import { McpTransport } from '../../packlets/mcp/transports';
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
// Fixture server — a real SDK Server advertising a mix of adaptable + un-adaptable tools.
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
/** The two adaptable tools (in the supported JSON Schema subset). */
|
|
50
|
+
const ADAPTABLE_TOOLS = [
|
|
51
|
+
{
|
|
52
|
+
name: 'echo',
|
|
53
|
+
description: 'Echoes the supplied message back.',
|
|
54
|
+
inputSchema: {
|
|
55
|
+
type: 'object',
|
|
56
|
+
properties: { msg: { type: 'string', description: 'message to echo' } },
|
|
57
|
+
required: ['msg']
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: 'ping',
|
|
62
|
+
description: 'Health check with no required args.',
|
|
63
|
+
inputSchema: { type: 'object', properties: {} }
|
|
64
|
+
}
|
|
65
|
+
];
|
|
66
|
+
/**
|
|
67
|
+
* One tool per JSON Schema feature `JsonSchema.fromJson` rejects. Each carries the forbidden
|
|
68
|
+
* keyword NESTED inside a property (the real-world shape: the top-level inputSchema is a valid
|
|
69
|
+
* `type: 'object'`, so the MCP SDK's own result validation lets it through, and the rejection
|
|
70
|
+
* happens in `adaptMcpTools` exactly as a real server would surface it).
|
|
71
|
+
*/
|
|
72
|
+
const UNADAPTABLE_TOOLS = [
|
|
73
|
+
{
|
|
74
|
+
name: 'ref_tool',
|
|
75
|
+
inputSchema: { type: 'object', properties: { x: { $ref: '#/$defs/Foo' } } }
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
name: 'oneof_tool',
|
|
79
|
+
inputSchema: { type: 'object', properties: { x: { oneOf: [{ type: 'string' }, { type: 'number' }] } } }
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: 'anyof_tool',
|
|
83
|
+
inputSchema: { type: 'object', properties: { x: { anyOf: [{ type: 'string' }, { type: 'number' }] } } }
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
name: 'pattern_tool',
|
|
87
|
+
inputSchema: { type: 'object', properties: { code: { type: 'string', pattern: '^[A-Z]+$' } } }
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
name: 'union_tool',
|
|
91
|
+
inputSchema: { type: 'object', properties: { x: { type: ['string', 'null'] } } }
|
|
92
|
+
}
|
|
93
|
+
];
|
|
94
|
+
const ALL_TOOLS = [...ADAPTABLE_TOOLS, ...UNADAPTABLE_TOOLS];
|
|
95
|
+
/** Builds and connects a real in-memory MCP server; returns its server-side handle for teardown. */
|
|
96
|
+
async function startFixtureServer() {
|
|
97
|
+
const server = new Server({ name: 'fixture-mcp-server', version: '0.0.1' }, { capabilities: { tools: {} } });
|
|
98
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ALL_TOOLS }));
|
|
99
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
100
|
+
const { name, arguments: args } = request.params;
|
|
101
|
+
if (name === 'echo') {
|
|
102
|
+
return { content: [{ type: 'text', text: `echo: ${JSON.stringify(args)}` }] };
|
|
103
|
+
}
|
|
104
|
+
if (name === 'ping') {
|
|
105
|
+
return { content: [{ type: 'text', text: 'pong' }] };
|
|
106
|
+
}
|
|
107
|
+
return { content: [{ type: 'text', text: `unknown tool: ${name}` }], isError: true };
|
|
108
|
+
});
|
|
109
|
+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
110
|
+
await server.connect(serverTransport);
|
|
111
|
+
return { server, clientTransport };
|
|
112
|
+
}
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// End-to-end suite
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
describe('@fgv/ts-extras-mcp end-to-end against a real in-memory MCP server', () => {
|
|
117
|
+
let server;
|
|
118
|
+
let session;
|
|
119
|
+
beforeEach(async () => {
|
|
120
|
+
const fixture = await startFixtureServer();
|
|
121
|
+
server = fixture.server;
|
|
122
|
+
// Wrap the SDK in-memory client transport in the package's opaque handle, then connect through
|
|
123
|
+
// the PUBLIC connectMcpSession (real Client + real initialize handshake). On a connect failure,
|
|
124
|
+
// tear the fixture server down before throwing so a failed handshake can't leak open handles.
|
|
125
|
+
const transport = new McpTransport('http', fixture.clientTransport);
|
|
126
|
+
const connectResult = await connectMcpSession({ transport, clientName: 'e2e', clientVersion: '0.0.0' });
|
|
127
|
+
if (connectResult.isFailure()) {
|
|
128
|
+
await server.close();
|
|
129
|
+
throw new Error(`fixture connect failed: ${connectResult.message}`);
|
|
130
|
+
}
|
|
131
|
+
session = connectResult.value;
|
|
132
|
+
});
|
|
133
|
+
afterEach(async () => {
|
|
134
|
+
// Assert teardown succeeds — a regression in close/transport would otherwise pass silently.
|
|
135
|
+
// `server.close()` runs in `finally` so the fixture is always torn down even if the assertion
|
|
136
|
+
// throws (otherwise a failed close would leak handles and make later tests flaky).
|
|
137
|
+
try {
|
|
138
|
+
expect(await closeMcpSession(session)).toSucceedWith(true);
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
await server.close();
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
test('the initialize handshake reports the real server identity', () => {
|
|
145
|
+
expect(session.serverInfo).toEqual({ name: 'fixture-mcp-server', version: '0.0.1' });
|
|
146
|
+
});
|
|
147
|
+
test('listMcpTools returns the full catalog over the real transport', async () => {
|
|
148
|
+
expect(await listMcpTools(session)).toSucceedAndSatisfy((tools) => {
|
|
149
|
+
expect(tools.map((t) => t.name).sort()).toEqual(['anyof_tool', 'echo', 'oneof_tool', 'pattern_tool', 'ping', 'ref_tool', 'union_tool'].sort());
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
test('callMcpTool round-trips a real tool result, and maps isError to Failure', async () => {
|
|
153
|
+
expect(await callMcpTool(session, 'echo', { msg: 'hi' })).toSucceedWith({
|
|
154
|
+
content: 'echo: {"msg":"hi"}'
|
|
155
|
+
});
|
|
156
|
+
expect(await callMcpTool(session, 'nope', {})).toFailWith(/unknown tool: nope/);
|
|
157
|
+
});
|
|
158
|
+
// =========================================================================
|
|
159
|
+
// CONSTRAINT 1 — graceful degradation with NOISY, schema-bearing warnings.
|
|
160
|
+
// =========================================================================
|
|
161
|
+
describe('Constraint 1 — adaptMcpTools graceful + NOISY degradation', () => {
|
|
162
|
+
test('excludes EVERY un-adaptable tool from `tools`, surfaces each on `skipped`, warns with the raw schema', async () => {
|
|
163
|
+
const logger = new Logging.InMemoryLogger('all');
|
|
164
|
+
const expectedReasonFragment = {
|
|
165
|
+
ref_tool: /\$ref/,
|
|
166
|
+
oneof_tool: /oneOf/,
|
|
167
|
+
anyof_tool: /anyOf/,
|
|
168
|
+
pattern_tool: /pattern/,
|
|
169
|
+
union_tool: /union 'type'/
|
|
170
|
+
};
|
|
171
|
+
expect(await adaptMcpTools(session, { logger })).toSucceedAndSatisfy((result) => {
|
|
172
|
+
// (a) Only the adaptable tools are offered to the model; none of the rejected ones leak.
|
|
173
|
+
expect(result.tools.map((t) => t.config.name).sort()).toEqual(['echo', 'ping']);
|
|
174
|
+
const offeredNames = new Set(result.tools.map((t) => t.config.name));
|
|
175
|
+
for (const t of UNADAPTABLE_TOOLS) {
|
|
176
|
+
expect(offeredNames.has(t.name)).toBe(false);
|
|
177
|
+
}
|
|
178
|
+
// (b) Each un-adaptable tool is surfaced structurally with name + JSON-pointer reason + the
|
|
179
|
+
// RAW failing schema (verbatim, so the subset can be widened later).
|
|
180
|
+
expect(result.skipped).toHaveLength(UNADAPTABLE_TOOLS.length);
|
|
181
|
+
const skippedByName = new Map(result.skipped.map((s) => [s.name, s]));
|
|
182
|
+
for (const tool of UNADAPTABLE_TOOLS) {
|
|
183
|
+
const skipped = skippedByName.get(tool.name);
|
|
184
|
+
expect(skipped).toBeDefined();
|
|
185
|
+
// JSON-pointer path into the offending node.
|
|
186
|
+
expect(skipped === null || skipped === void 0 ? void 0 : skipped.reason).toMatch(/#\/properties\//);
|
|
187
|
+
expect(skipped === null || skipped === void 0 ? void 0 : skipped.reason).toMatch(expectedReasonFragment[tool.name]);
|
|
188
|
+
// The RAW failing schema, verbatim.
|
|
189
|
+
expect(skipped === null || skipped === void 0 ? void 0 : skipped.schema).toEqual(tool.inputSchema);
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
// (c) A NOISY warning per skip that INCLUDES the raw failing schema text + the reason. The
|
|
193
|
+
// schema-in-the-warning is the whole "so we can extend fromJson later" requirement — a
|
|
194
|
+
// warn WITHOUT the schema would fail this assertion.
|
|
195
|
+
const warned = logger.logged.join('\n');
|
|
196
|
+
for (const tool of UNADAPTABLE_TOOLS) {
|
|
197
|
+
expect(warned).toContain(`skipping tool '${tool.name}'`);
|
|
198
|
+
// The raw schema, serialized exactly as adaptMcpTools emits it, must appear in the warn.
|
|
199
|
+
expect(warned).toContain(JSON.stringify(tool.inputSchema));
|
|
200
|
+
}
|
|
201
|
+
// And the reason fragments are present in the warnings too.
|
|
202
|
+
expect(warned).toMatch(/\$ref/);
|
|
203
|
+
expect(warned).toMatch(/union 'type'/);
|
|
204
|
+
});
|
|
205
|
+
test('an adapted tool executes end-to-end against the real server', async () => {
|
|
206
|
+
// Result-matcher-driven: extract the adapted `echo` tool inside the success satisfier (where
|
|
207
|
+
// its presence is asserted), then drive its execute callback — which round-trips through
|
|
208
|
+
// callMcpTool to the real server — with another matcher.
|
|
209
|
+
let echoExecute;
|
|
210
|
+
expect(await adaptMcpTools(session)).toSucceedAndSatisfy((result) => {
|
|
211
|
+
const echo = result.tools.find((t) => t.config.name === 'echo');
|
|
212
|
+
expect(echo).toBeDefined();
|
|
213
|
+
echoExecute = echo === null || echo === void 0 ? void 0 : echo.execute;
|
|
214
|
+
});
|
|
215
|
+
expect(echoExecute).toBeDefined();
|
|
216
|
+
expect(await (echoExecute === null || echoExecute === void 0 ? void 0 : echoExecute({ msg: 'roundtrip' }))).toSucceedWith('echo: {"msg":"roundtrip"}');
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
//# sourceMappingURL=endToEnd.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endToEnd.test.js","sourceRoot":"","sources":["../../../src/test/unit/endToEnd.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;;GAUG;AAEH,OAAO,oBAAoB,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAe,MAAM,eAAe,CAAC;AAErD,iGAAiG;AACjG,sFAAsF;AACtF,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAEnG,OAAO,EAEL,aAAa,EACb,WAAW,EACX,eAAe,EACf,iBAAiB,EACjB,YAAY,EACb,MAAM,oBAAoB,CAAC;AAC5B,mGAAmG;AACnG,+FAA+F;AAC/F,iFAAiF;AACjF,yDAAyD;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAE7D,8EAA8E;AAC9E,0FAA0F;AAC1F,8EAA8E;AAE9E,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AAI,CAAC,6DAA6D,EAAE,KAAK,IAAI,EAAE;YAC7E,6FAA6F;YAC7F,yFAAyF;YACzF,yDAAyD;YACzD,IAAI,WAAsE,CAAC;YAC3E,MAAM,CAAC,MAAM,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,MAAM,EAAE,EAAE;gBAClE,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;gBAChE,MAAM,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;gBAC3B,WAAW,GAAG,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC;YAC9B,CAAC,CAAC,CAAC;YACH,MAAM,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC;YAClC,MAAM,CAAC,MAAM,CAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAG,EAAE,GAAG,EAAE,WAAW,EAAE,CAAC,CAAA,CAAC,CAAC,aAAa,CAAC,2BAA2B,CAAC,CAAC;QAC/F,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,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 * End-to-end verification against a REAL in-memory MCP server (the SDK's `Server` +\n * `InMemoryTransport.createLinkedPair()`) — NOT a mocked SDK. This is the durable proof that the\n * brief's two load-bearing constraints actually flow through the full stack: the real SDK `Client`,\n * the real initialize handshake, the real `listTools`/`callTool` round-trips, the `sdk.ts`\n * projection casts, and `adaptMcpTools`' `JsonSchema.fromJson` gate. It is the class of gap that\n * 100%-line-coverage of a mocked seam cannot catch (e.g. a projection-shape mismatch in `sdk.ts`).\n *\n * The fixture server advertises a MIX of tools: two adaptable, and one for each JSON Schema feature\n * `JsonSchema.fromJson` rejects ($ref, oneOf, anyOf, pattern, union `type[]`).\n */\n\nimport '@fgv/ts-utils-jest';\nimport { Logging, type Result } from '@fgv/ts-utils';\n\n// Real MCP SDK server side — exercised over an in-process linked transport pair. Subpath imports\n// resolve via the tsconfig `paths` mapping (the same seam the package's sdk.ts uses).\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\n\nimport {\n type IMcpSession,\n adaptMcpTools,\n callMcpTool,\n closeMcpSession,\n connectMcpSession,\n listMcpTools\n} from '../../packlets/mcp';\n// Internal: the opaque-handle class. The package exposes only stdio/http transport factories, so a\n// real in-process e2e (which must inject the SDK's InMemoryTransport) wraps it here. Tests may\n// import internal modules directly (TESTING_GUIDELINES § Testing Internal Code).\n// eslint-disable-next-line @rushstack/packlets/mechanics\nimport { McpTransport } from '../../packlets/mcp/transports';\n\n// ---------------------------------------------------------------------------\n// Fixture server — a real SDK Server advertising a mix of adaptable + un-adaptable tools.\n// ---------------------------------------------------------------------------\n\n/** The two adaptable tools (in the supported JSON Schema subset). */\nconst ADAPTABLE_TOOLS = [\n {\n name: 'echo',\n description: 'Echoes the supplied message back.',\n inputSchema: {\n type: 'object',\n properties: { msg: { type: 'string', description: 'message to echo' } },\n required: ['msg']\n }\n },\n {\n name: 'ping',\n description: 'Health check with no required args.',\n inputSchema: { type: 'object', properties: {} }\n }\n];\n\n/**\n * One tool per JSON Schema feature `JsonSchema.fromJson` rejects. Each carries the forbidden\n * keyword NESTED inside a property (the real-world shape: the top-level inputSchema is a valid\n * `type: 'object'`, so the MCP SDK's own result validation lets it through, and the rejection\n * happens in `adaptMcpTools` exactly as a real server would surface it).\n */\nconst UNADAPTABLE_TOOLS = [\n {\n name: 'ref_tool',\n inputSchema: { type: 'object', properties: { x: { $ref: '#/$defs/Foo' } } }\n },\n {\n name: 'oneof_tool',\n inputSchema: { type: 'object', properties: { x: { oneOf: [{ type: 'string' }, { type: 'number' }] } } }\n },\n {\n name: 'anyof_tool',\n inputSchema: { type: 'object', properties: { x: { anyOf: [{ type: 'string' }, { type: 'number' }] } } }\n },\n {\n name: 'pattern_tool',\n inputSchema: { type: 'object', properties: { code: { type: 'string', pattern: '^[A-Z]+$' } } }\n },\n {\n name: 'union_tool',\n inputSchema: { type: 'object', properties: { x: { type: ['string', 'null'] } } }\n }\n];\n\nconst ALL_TOOLS = [...ADAPTABLE_TOOLS, ...UNADAPTABLE_TOOLS];\n\n/** Builds and connects a real in-memory MCP server; returns its server-side handle for teardown. */\nasync function startFixtureServer(): Promise<{ server: Server; clientTransport: InMemoryTransport }> {\n const server = new Server(\n { name: 'fixture-mcp-server', version: '0.0.1' },\n { capabilities: { tools: {} } }\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ALL_TOOLS }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n if (name === 'echo') {\n return { content: [{ type: 'text', text: `echo: ${JSON.stringify(args)}` }] };\n }\n if (name === 'ping') {\n return { content: [{ type: 'text', text: 'pong' }] };\n }\n return { content: [{ type: 'text', text: `unknown tool: ${name}` }], isError: true };\n });\n\n const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();\n await server.connect(serverTransport);\n return { server, clientTransport };\n}\n\n// ---------------------------------------------------------------------------\n// End-to-end suite\n// ---------------------------------------------------------------------------\n\ndescribe('@fgv/ts-extras-mcp end-to-end against a real in-memory MCP server', () => {\n let server: Server;\n let session: IMcpSession;\n\n beforeEach(async () => {\n const fixture = await startFixtureServer();\n server = fixture.server;\n // Wrap the SDK in-memory client transport in the package's opaque handle, then connect through\n // the PUBLIC connectMcpSession (real Client + real initialize handshake). On a connect failure,\n // tear the fixture server down before throwing so a failed handshake can't leak open handles.\n const transport = new McpTransport('http', fixture.clientTransport);\n const connectResult = await connectMcpSession({ transport, clientName: 'e2e', clientVersion: '0.0.0' });\n if (connectResult.isFailure()) {\n await server.close();\n throw new Error(`fixture connect failed: ${connectResult.message}`);\n }\n session = connectResult.value;\n });\n\n afterEach(async () => {\n // Assert teardown succeeds — a regression in close/transport would otherwise pass silently.\n // `server.close()` runs in `finally` so the fixture is always torn down even if the assertion\n // throws (otherwise a failed close would leak handles and make later tests flaky).\n try {\n expect(await closeMcpSession(session)).toSucceedWith(true);\n } finally {\n await server.close();\n }\n });\n\n test('the initialize handshake reports the real server identity', () => {\n expect(session.serverInfo).toEqual({ name: 'fixture-mcp-server', version: '0.0.1' });\n });\n\n test('listMcpTools returns the full catalog over the real transport', async () => {\n expect(await listMcpTools(session)).toSucceedAndSatisfy((tools) => {\n expect(tools.map((t) => t.name).sort()).toEqual(\n ['anyof_tool', 'echo', 'oneof_tool', 'pattern_tool', 'ping', 'ref_tool', 'union_tool'].sort()\n );\n });\n });\n\n test('callMcpTool round-trips a real tool result, and maps isError to Failure', async () => {\n expect(await callMcpTool(session, 'echo', { msg: 'hi' })).toSucceedWith({\n content: 'echo: {\"msg\":\"hi\"}'\n });\n expect(await callMcpTool(session, 'nope', {})).toFailWith(/unknown tool: nope/);\n });\n\n // =========================================================================\n // CONSTRAINT 1 — graceful degradation with NOISY, schema-bearing warnings.\n // =========================================================================\n describe('Constraint 1 — adaptMcpTools graceful + NOISY degradation', () => {\n test('excludes EVERY un-adaptable tool from `tools`, surfaces each on `skipped`, warns with the raw schema', async () => {\n const logger = new Logging.InMemoryLogger('all');\n const expectedReasonFragment: Record<string, RegExp> = {\n ref_tool: /\\$ref/,\n oneof_tool: /oneOf/,\n anyof_tool: /anyOf/,\n pattern_tool: /pattern/,\n union_tool: /union 'type'/\n };\n\n expect(await adaptMcpTools(session, { logger })).toSucceedAndSatisfy((result) => {\n // (a) Only the adaptable tools are offered to the model; none of the rejected ones leak.\n expect(result.tools.map((t) => t.config.name).sort()).toEqual(['echo', 'ping']);\n const offeredNames = new Set(result.tools.map((t) => t.config.name));\n for (const t of UNADAPTABLE_TOOLS) {\n expect(offeredNames.has(t.name)).toBe(false);\n }\n\n // (b) Each un-adaptable tool is surfaced structurally with name + JSON-pointer reason + the\n // RAW failing schema (verbatim, so the subset can be widened later).\n expect(result.skipped).toHaveLength(UNADAPTABLE_TOOLS.length);\n const skippedByName = new Map(result.skipped.map((s) => [s.name, s]));\n for (const tool of UNADAPTABLE_TOOLS) {\n const skipped = skippedByName.get(tool.name);\n expect(skipped).toBeDefined();\n // JSON-pointer path into the offending node.\n expect(skipped?.reason).toMatch(/#\\/properties\\//);\n expect(skipped?.reason).toMatch(expectedReasonFragment[tool.name]);\n // The RAW failing schema, verbatim.\n expect(skipped?.schema).toEqual(tool.inputSchema);\n }\n });\n\n // (c) A NOISY warning per skip that INCLUDES the raw failing schema text + the reason. The\n // schema-in-the-warning is the whole \"so we can extend fromJson later\" requirement — a\n // warn WITHOUT the schema would fail this assertion.\n const warned = logger.logged.join('\\n');\n for (const tool of UNADAPTABLE_TOOLS) {\n expect(warned).toContain(`skipping tool '${tool.name}'`);\n // The raw schema, serialized exactly as adaptMcpTools emits it, must appear in the warn.\n expect(warned).toContain(JSON.stringify(tool.inputSchema));\n }\n // And the reason fragments are present in the warnings too.\n expect(warned).toMatch(/\\$ref/);\n expect(warned).toMatch(/union 'type'/);\n });\n\n test('an adapted tool executes end-to-end against the real server', async () => {\n // Result-matcher-driven: extract the adapted `echo` tool inside the success satisfier (where\n // its presence is asserted), then drive its execute callback — which round-trips through\n // callMcpTool to the real server — with another matcher.\n let echoExecute: ((args: unknown) => Promise<Result<unknown>>) | undefined;\n expect(await adaptMcpTools(session)).toSucceedAndSatisfy((result) => {\n const echo = result.tools.find((t) => t.config.name === 'echo');\n expect(echo).toBeDefined();\n echoExecute = echo?.execute;\n });\n expect(echoExecute).toBeDefined();\n expect(await echoExecute?.({ msg: 'roundtrip' })).toSucceedWith('echo: {\"msg\":\"roundtrip\"}');\n });\n });\n});\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
import '@fgv/ts-utils-jest';
|
|
23
|
+
import * as mcp from '../../index';
|
|
24
|
+
describe('@fgv/ts-extras-mcp package barrel', () => {
|
|
25
|
+
test('re-exports the public boundary primitives', () => {
|
|
26
|
+
expect(typeof mcp.createStdioTransport).toBe('function');
|
|
27
|
+
expect(typeof mcp.createHttpTransport).toBe('function');
|
|
28
|
+
expect(typeof mcp.connectMcpSession).toBe('function');
|
|
29
|
+
expect(typeof mcp.closeMcpSession).toBe('function');
|
|
30
|
+
expect(typeof mcp.listMcpTools).toBe('function');
|
|
31
|
+
expect(typeof mcp.callMcpTool).toBe('function');
|
|
32
|
+
expect(typeof mcp.adaptMcpTools).toBe('function');
|
|
33
|
+
});
|
|
34
|
+
test('the re-exported transport factories are the real (behaving) implementations', () => {
|
|
35
|
+
// Behavioral signal beyond `typeof`: a renamed-but-still-a-function export would not behave
|
|
36
|
+
// this way. (The synchronous transport factories validate without touching the SDK/network.)
|
|
37
|
+
expect(mcp.createStdioTransport({ command: '' })).toFailWith(/command must be a non-empty string/);
|
|
38
|
+
expect(mcp.createHttpTransport({ url: 'not a url' })).toFailWith(/invalid url/);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
//# sourceMappingURL=index.test.js.map
|