@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.
Files changed (107) hide show
  1. package/.rush/temp/5d207610a84e494acaefe7ed13447cda74ddf7da.tar.log +90 -0
  2. package/.rush/temp/chunked-rush-logs/ts-extras-mcp.build.chunks.jsonl +9 -0
  3. package/.rush/temp/operation/build/all.log +9 -0
  4. package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
  5. package/.rush/temp/operation/build/state.json +3 -0
  6. package/.rush/temp/shrinkwrap-deps.json +734 -0
  7. package/CHANGELOG.json +4 -0
  8. package/README.md +133 -0
  9. package/config/api-extractor.json +38 -0
  10. package/config/jest.config.json +13 -0
  11. package/config/rig.json +6 -0
  12. package/dist/index.js +49 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/packlets/mcp/adapter.js +122 -0
  15. package/dist/packlets/mcp/adapter.js.map +1 -0
  16. package/dist/packlets/mcp/index.js +33 -0
  17. package/dist/packlets/mcp/index.js.map +1 -0
  18. package/dist/packlets/mcp/model.js +23 -0
  19. package/dist/packlets/mcp/model.js.map +1 -0
  20. package/dist/packlets/mcp/operations.js +119 -0
  21. package/dist/packlets/mcp/operations.js.map +1 -0
  22. package/dist/packlets/mcp/sdk.js +67 -0
  23. package/dist/packlets/mcp/sdk.js.map +1 -0
  24. package/dist/packlets/mcp/session.js +109 -0
  25. package/dist/packlets/mcp/session.js.map +1 -0
  26. package/dist/packlets/mcp/transports.js +96 -0
  27. package/dist/packlets/mcp/transports.js.map +1 -0
  28. package/dist/test/unit/endToEnd.test.js +220 -0
  29. package/dist/test/unit/endToEnd.test.js.map +1 -0
  30. package/dist/test/unit/index.test.js +41 -0
  31. package/dist/test/unit/index.test.js.map +1 -0
  32. package/dist/test/unit/mcp.test.js +381 -0
  33. package/dist/test/unit/mcp.test.js.map +1 -0
  34. package/dist/test/unit/sdk.test.js +68 -0
  35. package/dist/test/unit/sdk.test.js.map +1 -0
  36. package/dist/ts-extras-mcp.d.ts +290 -0
  37. package/dist/tsdoc-metadata.json +11 -0
  38. package/eslint.config.js +15 -0
  39. package/etc/ts-extras-mcp.api.md +104 -0
  40. package/lib/index.d.ts +28 -0
  41. package/lib/index.d.ts.map +1 -0
  42. package/lib/index.js +65 -0
  43. package/lib/index.js.map +1 -0
  44. package/lib/packlets/mcp/adapter.d.ts +33 -0
  45. package/lib/packlets/mcp/adapter.d.ts.map +1 -0
  46. package/lib/packlets/mcp/adapter.js +125 -0
  47. package/lib/packlets/mcp/adapter.js.map +1 -0
  48. package/lib/packlets/mcp/index.d.ts +10 -0
  49. package/lib/packlets/mcp/index.d.ts.map +1 -0
  50. package/lib/packlets/mcp/index.js +57 -0
  51. package/lib/packlets/mcp/index.js.map +1 -0
  52. package/lib/packlets/mcp/model.d.ts +155 -0
  53. package/lib/packlets/mcp/model.d.ts.map +1 -0
  54. package/lib/packlets/mcp/model.js +24 -0
  55. package/lib/packlets/mcp/model.js.map +1 -0
  56. package/lib/packlets/mcp/operations.d.ts +36 -0
  57. package/lib/packlets/mcp/operations.d.ts.map +1 -0
  58. package/lib/packlets/mcp/operations.js +123 -0
  59. package/lib/packlets/mcp/operations.js.map +1 -0
  60. package/lib/packlets/mcp/sdk.d.ts +91 -0
  61. package/lib/packlets/mcp/sdk.d.ts.map +1 -0
  62. package/lib/packlets/mcp/sdk.js +72 -0
  63. package/lib/packlets/mcp/sdk.js.map +1 -0
  64. package/lib/packlets/mcp/session.d.ts +43 -0
  65. package/lib/packlets/mcp/session.d.ts.map +1 -0
  66. package/lib/packlets/mcp/session.js +115 -0
  67. package/lib/packlets/mcp/session.js.map +1 -0
  68. package/lib/packlets/mcp/transports.d.ts +49 -0
  69. package/lib/packlets/mcp/transports.d.ts.map +1 -0
  70. package/lib/packlets/mcp/transports.js +102 -0
  71. package/lib/packlets/mcp/transports.js.map +1 -0
  72. package/lib/test/unit/endToEnd.test.d.ts +13 -0
  73. package/lib/test/unit/endToEnd.test.d.ts.map +1 -0
  74. package/lib/test/unit/endToEnd.test.js +222 -0
  75. package/lib/test/unit/endToEnd.test.js.map +1 -0
  76. package/lib/test/unit/index.test.d.ts +2 -0
  77. package/lib/test/unit/index.test.d.ts.map +1 -0
  78. package/lib/test/unit/index.test.js +76 -0
  79. package/lib/test/unit/index.test.js.map +1 -0
  80. package/lib/test/unit/mcp.test.d.ts +2 -0
  81. package/lib/test/unit/mcp.test.d.ts.map +1 -0
  82. package/lib/test/unit/mcp.test.js +416 -0
  83. package/lib/test/unit/mcp.test.js.map +1 -0
  84. package/lib/test/unit/sdk.test.d.ts +2 -0
  85. package/lib/test/unit/sdk.test.d.ts.map +1 -0
  86. package/lib/test/unit/sdk.test.js +70 -0
  87. package/lib/test/unit/sdk.test.js.map +1 -0
  88. package/package.json +86 -0
  89. package/rush-logs/ts-extras-mcp.build.cache.log +3 -0
  90. package/rush-logs/ts-extras-mcp.build.log +9 -0
  91. package/src/index.ts +50 -0
  92. package/src/packlets/mcp/adapter.ts +152 -0
  93. package/src/packlets/mcp/index.ts +34 -0
  94. package/src/packlets/mcp/model.ts +204 -0
  95. package/src/packlets/mcp/operations.ts +138 -0
  96. package/src/packlets/mcp/sdk.ts +148 -0
  97. package/src/packlets/mcp/session.ts +137 -0
  98. package/src/packlets/mcp/transports.ts +111 -0
  99. package/src/test/unit/endToEnd.test.ts +254 -0
  100. package/src/test/unit/index.test.ts +43 -0
  101. package/src/test/unit/mcp.test.ts +473 -0
  102. package/src/test/unit/sdk.test.ts +73 -0
  103. package/temp/build/lint/_eslint-5eVG3S6w.json +54 -0
  104. package/temp/build/typescript/ts_8nwakTlr.json +1 -0
  105. package/temp/ts-extras-mcp.api.json +1662 -0
  106. package/temp/ts-extras-mcp.api.md +104 -0
  107. package/tsconfig.json +12 -0
@@ -0,0 +1,148 @@
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
+ /**
24
+ * **The single `@modelcontextprotocol/sdk` import site for the entire package.**
25
+ *
26
+ * Every other module in `@fgv/ts-extras-mcp` depends only on the minimal local projection
27
+ * exported here (`ISdkClient`, `ISdkTransport`, the three `make*` factories) — never on the SDK
28
+ * directly. This keeps the announced v2 client-package rename a one-file change and lets unit
29
+ * tests mock this module instead of the SDK internals (no live server required).
30
+ *
31
+ * The only `as unknown as` casts in the package live here, at the boundary where the real SDK
32
+ * objects are narrowed to the local projection.
33
+ *
34
+ * @internal
35
+ */
36
+
37
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
38
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
39
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
40
+
41
+ /**
42
+ * Opaque transport handle. The concrete value is an SDK `Transport`; consumers of this module
43
+ * treat it as opaque and only ever hand it back to {@link makeClient}-produced clients.
44
+ * @internal
45
+ */
46
+ export type ISdkTransport = object;
47
+
48
+ /**
49
+ * A single content block in an MCP `CallToolResult`. Only `text` blocks carry inline content;
50
+ * all other block types are projected to a structural summary by the operations layer.
51
+ * @internal
52
+ */
53
+ export interface ISdkContentBlock {
54
+ readonly type: string;
55
+ readonly text?: string;
56
+ }
57
+
58
+ /**
59
+ * Projection of the SDK's `CallToolResult`.
60
+ * @internal
61
+ */
62
+ export interface ISdkCallToolResult {
63
+ readonly content?: ReadonlyArray<ISdkContentBlock>;
64
+ readonly isError?: boolean;
65
+ }
66
+
67
+ /**
68
+ * Projection of a single tool descriptor in the SDK's `ListToolsResult`.
69
+ * @internal
70
+ */
71
+ export interface ISdkToolDescriptor {
72
+ readonly name: string;
73
+ readonly description?: string;
74
+ readonly inputSchema?: unknown;
75
+ }
76
+
77
+ /**
78
+ * Projection of the SDK's `ListToolsResult` (one page).
79
+ * @internal
80
+ */
81
+ export interface ISdkListToolsResult {
82
+ readonly tools: ReadonlyArray<ISdkToolDescriptor>;
83
+ readonly nextCursor?: string;
84
+ }
85
+
86
+ /**
87
+ * Server identity returned by the SDK's `getServerVersion()` after the initialize handshake.
88
+ * @internal
89
+ */
90
+ export interface ISdkImplementation {
91
+ readonly name: string;
92
+ readonly version: string;
93
+ }
94
+
95
+ /**
96
+ * Minimal projection of the SDK `Client` surface the package depends on.
97
+ * @internal
98
+ */
99
+ export interface ISdkClient {
100
+ connect(transport: ISdkTransport): Promise<void>;
101
+ getServerVersion(): ISdkImplementation | undefined;
102
+ listTools(params?: { cursor?: string }): Promise<ISdkListToolsResult>;
103
+ callTool(params: { name: string; arguments?: Record<string, unknown> }): Promise<ISdkCallToolResult>;
104
+ close(): Promise<void>;
105
+ }
106
+
107
+ /**
108
+ * Parameters for the stdio transport factory.
109
+ * @internal
110
+ */
111
+ export interface ISdkStdioParams {
112
+ readonly command: string;
113
+ readonly args?: ReadonlyArray<string>;
114
+ readonly env?: Record<string, string>;
115
+ readonly cwd?: string;
116
+ }
117
+
118
+ /**
119
+ * Constructs an MCP client. The `as unknown as` cast is the package's single SDK-type
120
+ * bridge — the runtime object is a real SDK `Client`.
121
+ * @internal
122
+ */
123
+ export function makeClient(name: string, version: string): ISdkClient {
124
+ return new Client({ name, version }, { capabilities: {} }) as unknown as ISdkClient;
125
+ }
126
+
127
+ /**
128
+ * Constructs a stdio transport that spawns the given command as a subprocess.
129
+ * @internal
130
+ */
131
+ export function makeStdioTransport(params: ISdkStdioParams): ISdkTransport {
132
+ return new StdioClientTransport({
133
+ command: params.command,
134
+ args: params.args ? [...params.args] : undefined,
135
+ env: params.env,
136
+ cwd: params.cwd
137
+ }) as unknown as ISdkTransport;
138
+ }
139
+
140
+ /**
141
+ * Constructs a Streamable-HTTP transport for the given URL, with optional static headers.
142
+ * @internal
143
+ */
144
+ export function makeHttpTransport(url: URL, headers?: Record<string, string>): ISdkTransport {
145
+ return new StreamableHTTPClientTransport(url, {
146
+ requestInit: headers ? { headers } : undefined
147
+ }) as unknown as ISdkTransport;
148
+ }
@@ -0,0 +1,137 @@
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
+ /**
24
+ * Session lifecycle — connect / close, converting the throwing SDK calls into `Result<T>`.
25
+ * @packageDocumentation
26
+ */
27
+
28
+ import { type Result, captureAsyncResult, fail, succeed } from '@fgv/ts-utils';
29
+
30
+ import { type IConnectMcpSessionParams, type IMcpServerInfo, type IMcpSession } from './model';
31
+ import { type ISdkClient, makeClient } from './sdk';
32
+ import { McpTransport } from './transports';
33
+
34
+ /** Default client name advertised during the initialize handshake. */
35
+ const DEFAULT_CLIENT_NAME: string = '@fgv/ts-extras-mcp';
36
+ /**
37
+ * Default client version advertised during the initialize handshake.
38
+ *
39
+ * @remarks
40
+ * Keep in sync with this package's `package.json` version on each release. It is informational
41
+ * only — MCP servers use it for logging/telemetry, not for behavior — so a drift is low-impact,
42
+ * but it should be bumped alongside the lockstep version. (Reading it from `package.json` at
43
+ * runtime is avoided to keep the bundle free of a JSON import / `require` of the manifest.)
44
+ */
45
+ const DEFAULT_CLIENT_VERSION: string = '5.1.0';
46
+
47
+ /**
48
+ * Concrete session handle. Packlet-internal — carries the live SDK client that the operations
49
+ * layer recovers via {@link McpSession.fromHandle}. Not exported from the package barrel.
50
+ * @internal
51
+ */
52
+ export class McpSession implements IMcpSession {
53
+ public readonly clientName: string;
54
+ public readonly clientVersion: string;
55
+ public readonly serverInfo: IMcpServerInfo | undefined;
56
+ /** The live SDK client. */
57
+ public readonly client: ISdkClient;
58
+
59
+ public constructor(
60
+ client: ISdkClient,
61
+ clientName: string,
62
+ clientVersion: string,
63
+ serverInfo: IMcpServerInfo | undefined
64
+ ) {
65
+ this.client = client;
66
+ this.clientName = clientName;
67
+ this.clientVersion = clientVersion;
68
+ this.serverInfo = serverInfo;
69
+ }
70
+
71
+ /**
72
+ * Narrows a public {@link IMcpSession} handle back to the concrete {@link McpSession}. Fails
73
+ * loudly when handed a foreign object that did not originate from {@link connectMcpSession}.
74
+ */
75
+ public static fromHandle(handle: IMcpSession): Result<McpSession> {
76
+ if (handle instanceof McpSession) {
77
+ return succeed(handle);
78
+ }
79
+ return fail('invalid MCP session: expected a handle from connectMcpSession');
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Connects to an MCP server over the given transport and performs the initialize handshake.
85
+ *
86
+ * @param params - Transport plus optional client identity and logger.
87
+ * @returns `Success` with an opaque {@link IMcpSession}, or `Failure` if the transport handle is
88
+ * foreign or the connection/handshake fails.
89
+ * @public
90
+ */
91
+ export async function connectMcpSession(params: IConnectMcpSessionParams): Promise<Result<IMcpSession>> {
92
+ const { transport, clientName, clientVersion, logger } = params;
93
+
94
+ const transportResult = McpTransport.fromHandle(transport);
95
+ if (transportResult.isFailure()) {
96
+ return fail(`connectMcpSession: ${transportResult.message}`);
97
+ }
98
+
99
+ const name = clientName ?? DEFAULT_CLIENT_NAME;
100
+ const version = clientVersion ?? DEFAULT_CLIENT_VERSION;
101
+ const client = makeClient(name, version);
102
+
103
+ logger?.info(
104
+ `mcp: connecting (client ${name}@${version}, transport ${transportResult.value.transportKind})`
105
+ );
106
+
107
+ return captureAsyncResult(() => client.connect(transportResult.value.sdkTransport))
108
+ .onSuccess(() => {
109
+ const raw = client.getServerVersion();
110
+ const serverInfo: IMcpServerInfo | undefined =
111
+ raw !== undefined ? { name: raw.name, version: raw.version } : undefined;
112
+ logger?.info(
113
+ serverInfo !== undefined
114
+ ? `mcp: connected to server ${serverInfo.name}@${serverInfo.version}`
115
+ : 'mcp: connected (server did not report identity)'
116
+ );
117
+ return succeed<IMcpSession>(new McpSession(client, name, version, serverInfo));
118
+ })
119
+ .withErrorFormat((msg) => `connectMcpSession: ${msg}`);
120
+ }
121
+
122
+ /**
123
+ * Closes an MCP session, tearing down the transport (and any spawned subprocess).
124
+ *
125
+ * @param session - A session from {@link connectMcpSession}.
126
+ * @returns `Success(true)`, or `Failure` if the handle is foreign or the close call throws.
127
+ * @public
128
+ */
129
+ export async function closeMcpSession(session: IMcpSession): Promise<Result<true>> {
130
+ const sessionResult = McpSession.fromHandle(session);
131
+ if (sessionResult.isFailure()) {
132
+ return fail(`closeMcpSession: ${sessionResult.message}`);
133
+ }
134
+ return captureAsyncResult(() => sessionResult.value.client.close())
135
+ .onSuccess(() => succeed(true as const))
136
+ .withErrorFormat((msg) => `closeMcpSession: ${msg}`);
137
+ }
@@ -0,0 +1,111 @@
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
+ /**
24
+ * Transport factories — convert the throwing SDK transport constructors into `Result<T>`.
25
+ * @packageDocumentation
26
+ */
27
+
28
+ import { type Result, captureResult, fail, succeed } from '@fgv/ts-utils';
29
+
30
+ import { type IMcpHttpTransportParams, type IMcpStdioTransportParams, type IMcpTransport } from './model';
31
+ import { type ISdkTransport, makeHttpTransport, makeStdioTransport } from './sdk';
32
+
33
+ /**
34
+ * Concrete transport handle. Packlet-internal — carries the SDK transport that
35
+ * {@link McpTransport.fromHandle} recovers inside {@link connectMcpSession}. Not exported from
36
+ * the package barrel, so it does not appear in the public API surface.
37
+ * @internal
38
+ */
39
+ export class McpTransport implements IMcpTransport {
40
+ public readonly transportKind: 'stdio' | 'http';
41
+ /** The wrapped SDK transport. */
42
+ public readonly sdkTransport: ISdkTransport;
43
+
44
+ public constructor(transportKind: 'stdio' | 'http', sdkTransport: ISdkTransport) {
45
+ this.transportKind = transportKind;
46
+ this.sdkTransport = sdkTransport;
47
+ }
48
+
49
+ /**
50
+ * Narrows a public {@link IMcpTransport} handle back to the concrete {@link McpTransport}.
51
+ * Fails loudly when handed a foreign object that did not originate from one of this
52
+ * package's transport factories.
53
+ */
54
+ public static fromHandle(handle: IMcpTransport): Result<McpTransport> {
55
+ if (handle instanceof McpTransport) {
56
+ return succeed(handle);
57
+ }
58
+ return fail('invalid MCP transport: expected a handle from createStdioTransport / createHttpTransport');
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Creates a stdio MCP transport that speaks MCP over the stdin/stdout of a spawned subprocess.
64
+ *
65
+ * @remarks
66
+ * **Security — trust boundary.** The transport spawns `params.command` (with `params.args`) as a
67
+ * child process. Never source the command or arguments from untrusted input; treat them with the
68
+ * same care as any shell-out. See the package README's security note.
69
+ *
70
+ * @param params - The command, arguments, environment, and working directory.
71
+ * @returns `Success` with an opaque transport handle, or `Failure` if the SDK constructor throws
72
+ * (e.g. an empty command).
73
+ * @public
74
+ */
75
+ export function createStdioTransport(params: IMcpStdioTransportParams): Result<IMcpTransport> {
76
+ if (params.command.trim().length === 0) {
77
+ return fail('createStdioTransport: command must be a non-empty string');
78
+ }
79
+ return captureResult(() =>
80
+ makeStdioTransport({
81
+ command: params.command,
82
+ args: params.args,
83
+ env: params.env,
84
+ cwd: params.cwd
85
+ })
86
+ )
87
+ .onSuccess((sdkTransport) => succeed<IMcpTransport>(new McpTransport('stdio', sdkTransport)))
88
+ .withErrorFormat((msg) => `createStdioTransport: ${msg}`);
89
+ }
90
+
91
+ /**
92
+ * Creates a Streamable-HTTP MCP transport for the given endpoint URL.
93
+ *
94
+ * @param params - The endpoint URL and optional static headers.
95
+ * @returns `Success` with an opaque transport handle, or `Failure` if the URL is invalid or the
96
+ * SDK constructor throws.
97
+ * @public
98
+ */
99
+ export function createHttpTransport(params: IMcpHttpTransportParams): Result<IMcpTransport> {
100
+ return captureResult(() => new URL(params.url))
101
+ .withErrorFormat(() => `invalid url '${params.url}'`)
102
+ .onSuccess((url): Result<IMcpTransport> => {
103
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
104
+ return fail(`url must use http or https protocol (got '${url.protocol}')`);
105
+ }
106
+ return captureResult(() => makeHttpTransport(url, params.headers)).onSuccess((sdkTransport) =>
107
+ succeed<IMcpTransport>(new McpTransport('http', sdkTransport))
108
+ );
109
+ })
110
+ .withErrorFormat((msg) => `createHttpTransport: ${msg}`);
111
+ }
@@ -0,0 +1,254 @@
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
+ /**
24
+ * End-to-end verification against a REAL in-memory MCP server (the SDK's `Server` +
25
+ * `InMemoryTransport.createLinkedPair()`) — NOT a mocked SDK. This is the durable proof that the
26
+ * brief's two load-bearing constraints actually flow through the full stack: the real SDK `Client`,
27
+ * the real initialize handshake, the real `listTools`/`callTool` round-trips, the `sdk.ts`
28
+ * projection casts, and `adaptMcpTools`' `JsonSchema.fromJson` gate. It is the class of gap that
29
+ * 100%-line-coverage of a mocked seam cannot catch (e.g. a projection-shape mismatch in `sdk.ts`).
30
+ *
31
+ * The fixture server advertises a MIX of tools: two adaptable, and one for each JSON Schema feature
32
+ * `JsonSchema.fromJson` rejects ($ref, oneOf, anyOf, pattern, union `type[]`).
33
+ */
34
+
35
+ import '@fgv/ts-utils-jest';
36
+ import { Logging, type Result } from '@fgv/ts-utils';
37
+
38
+ // Real MCP SDK server side — exercised over an in-process linked transport pair. Subpath imports
39
+ // resolve via the tsconfig `paths` mapping (the same seam the package's sdk.ts uses).
40
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
41
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
42
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
43
+
44
+ import {
45
+ type IMcpSession,
46
+ adaptMcpTools,
47
+ callMcpTool,
48
+ closeMcpSession,
49
+ connectMcpSession,
50
+ listMcpTools
51
+ } from '../../packlets/mcp';
52
+ // Internal: the opaque-handle class. The package exposes only stdio/http transport factories, so a
53
+ // real in-process e2e (which must inject the SDK's InMemoryTransport) wraps it here. Tests may
54
+ // import internal modules directly (TESTING_GUIDELINES § Testing Internal Code).
55
+ // eslint-disable-next-line @rushstack/packlets/mechanics
56
+ import { McpTransport } from '../../packlets/mcp/transports';
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // Fixture server — a real SDK Server advertising a mix of adaptable + un-adaptable tools.
60
+ // ---------------------------------------------------------------------------
61
+
62
+ /** The two adaptable tools (in the supported JSON Schema subset). */
63
+ const ADAPTABLE_TOOLS = [
64
+ {
65
+ name: 'echo',
66
+ description: 'Echoes the supplied message back.',
67
+ inputSchema: {
68
+ type: 'object',
69
+ properties: { msg: { type: 'string', description: 'message to echo' } },
70
+ required: ['msg']
71
+ }
72
+ },
73
+ {
74
+ name: 'ping',
75
+ description: 'Health check with no required args.',
76
+ inputSchema: { type: 'object', properties: {} }
77
+ }
78
+ ];
79
+
80
+ /**
81
+ * One tool per JSON Schema feature `JsonSchema.fromJson` rejects. Each carries the forbidden
82
+ * keyword NESTED inside a property (the real-world shape: the top-level inputSchema is a valid
83
+ * `type: 'object'`, so the MCP SDK's own result validation lets it through, and the rejection
84
+ * happens in `adaptMcpTools` exactly as a real server would surface it).
85
+ */
86
+ const UNADAPTABLE_TOOLS = [
87
+ {
88
+ name: 'ref_tool',
89
+ inputSchema: { type: 'object', properties: { x: { $ref: '#/$defs/Foo' } } }
90
+ },
91
+ {
92
+ name: 'oneof_tool',
93
+ inputSchema: { type: 'object', properties: { x: { oneOf: [{ type: 'string' }, { type: 'number' }] } } }
94
+ },
95
+ {
96
+ name: 'anyof_tool',
97
+ inputSchema: { type: 'object', properties: { x: { anyOf: [{ type: 'string' }, { type: 'number' }] } } }
98
+ },
99
+ {
100
+ name: 'pattern_tool',
101
+ inputSchema: { type: 'object', properties: { code: { type: 'string', pattern: '^[A-Z]+$' } } }
102
+ },
103
+ {
104
+ name: 'union_tool',
105
+ inputSchema: { type: 'object', properties: { x: { type: ['string', 'null'] } } }
106
+ }
107
+ ];
108
+
109
+ const ALL_TOOLS = [...ADAPTABLE_TOOLS, ...UNADAPTABLE_TOOLS];
110
+
111
+ /** Builds and connects a real in-memory MCP server; returns its server-side handle for teardown. */
112
+ async function startFixtureServer(): Promise<{ server: Server; clientTransport: InMemoryTransport }> {
113
+ const server = new Server(
114
+ { name: 'fixture-mcp-server', version: '0.0.1' },
115
+ { capabilities: { tools: {} } }
116
+ );
117
+
118
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ALL_TOOLS }));
119
+
120
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
121
+ const { name, arguments: args } = request.params;
122
+ if (name === 'echo') {
123
+ return { content: [{ type: 'text', text: `echo: ${JSON.stringify(args)}` }] };
124
+ }
125
+ if (name === 'ping') {
126
+ return { content: [{ type: 'text', text: 'pong' }] };
127
+ }
128
+ return { content: [{ type: 'text', text: `unknown tool: ${name}` }], isError: true };
129
+ });
130
+
131
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
132
+ await server.connect(serverTransport);
133
+ return { server, clientTransport };
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // End-to-end suite
138
+ // ---------------------------------------------------------------------------
139
+
140
+ describe('@fgv/ts-extras-mcp end-to-end against a real in-memory MCP server', () => {
141
+ let server: Server;
142
+ let session: IMcpSession;
143
+
144
+ beforeEach(async () => {
145
+ const fixture = await startFixtureServer();
146
+ server = fixture.server;
147
+ // Wrap the SDK in-memory client transport in the package's opaque handle, then connect through
148
+ // the PUBLIC connectMcpSession (real Client + real initialize handshake). On a connect failure,
149
+ // tear the fixture server down before throwing so a failed handshake can't leak open handles.
150
+ const transport = new McpTransport('http', fixture.clientTransport);
151
+ const connectResult = await connectMcpSession({ transport, clientName: 'e2e', clientVersion: '0.0.0' });
152
+ if (connectResult.isFailure()) {
153
+ await server.close();
154
+ throw new Error(`fixture connect failed: ${connectResult.message}`);
155
+ }
156
+ session = connectResult.value;
157
+ });
158
+
159
+ afterEach(async () => {
160
+ // Assert teardown succeeds — a regression in close/transport would otherwise pass silently.
161
+ // `server.close()` runs in `finally` so the fixture is always torn down even if the assertion
162
+ // throws (otherwise a failed close would leak handles and make later tests flaky).
163
+ try {
164
+ expect(await closeMcpSession(session)).toSucceedWith(true);
165
+ } finally {
166
+ await server.close();
167
+ }
168
+ });
169
+
170
+ test('the initialize handshake reports the real server identity', () => {
171
+ expect(session.serverInfo).toEqual({ name: 'fixture-mcp-server', version: '0.0.1' });
172
+ });
173
+
174
+ test('listMcpTools returns the full catalog over the real transport', async () => {
175
+ expect(await listMcpTools(session)).toSucceedAndSatisfy((tools) => {
176
+ expect(tools.map((t) => t.name).sort()).toEqual(
177
+ ['anyof_tool', 'echo', 'oneof_tool', 'pattern_tool', 'ping', 'ref_tool', 'union_tool'].sort()
178
+ );
179
+ });
180
+ });
181
+
182
+ test('callMcpTool round-trips a real tool result, and maps isError to Failure', async () => {
183
+ expect(await callMcpTool(session, 'echo', { msg: 'hi' })).toSucceedWith({
184
+ content: 'echo: {"msg":"hi"}'
185
+ });
186
+ expect(await callMcpTool(session, 'nope', {})).toFailWith(/unknown tool: nope/);
187
+ });
188
+
189
+ // =========================================================================
190
+ // CONSTRAINT 1 — graceful degradation with NOISY, schema-bearing warnings.
191
+ // =========================================================================
192
+ describe('Constraint 1 — adaptMcpTools graceful + NOISY degradation', () => {
193
+ test('excludes EVERY un-adaptable tool from `tools`, surfaces each on `skipped`, warns with the raw schema', async () => {
194
+ const logger = new Logging.InMemoryLogger('all');
195
+ const expectedReasonFragment: Record<string, RegExp> = {
196
+ ref_tool: /\$ref/,
197
+ oneof_tool: /oneOf/,
198
+ anyof_tool: /anyOf/,
199
+ pattern_tool: /pattern/,
200
+ union_tool: /union 'type'/
201
+ };
202
+
203
+ expect(await adaptMcpTools(session, { logger })).toSucceedAndSatisfy((result) => {
204
+ // (a) Only the adaptable tools are offered to the model; none of the rejected ones leak.
205
+ expect(result.tools.map((t) => t.config.name).sort()).toEqual(['echo', 'ping']);
206
+ const offeredNames = new Set(result.tools.map((t) => t.config.name));
207
+ for (const t of UNADAPTABLE_TOOLS) {
208
+ expect(offeredNames.has(t.name)).toBe(false);
209
+ }
210
+
211
+ // (b) Each un-adaptable tool is surfaced structurally with name + JSON-pointer reason + the
212
+ // RAW failing schema (verbatim, so the subset can be widened later).
213
+ expect(result.skipped).toHaveLength(UNADAPTABLE_TOOLS.length);
214
+ const skippedByName = new Map(result.skipped.map((s) => [s.name, s]));
215
+ for (const tool of UNADAPTABLE_TOOLS) {
216
+ const skipped = skippedByName.get(tool.name);
217
+ expect(skipped).toBeDefined();
218
+ // JSON-pointer path into the offending node.
219
+ expect(skipped?.reason).toMatch(/#\/properties\//);
220
+ expect(skipped?.reason).toMatch(expectedReasonFragment[tool.name]);
221
+ // The RAW failing schema, verbatim.
222
+ expect(skipped?.schema).toEqual(tool.inputSchema);
223
+ }
224
+ });
225
+
226
+ // (c) A NOISY warning per skip that INCLUDES the raw failing schema text + the reason. The
227
+ // schema-in-the-warning is the whole "so we can extend fromJson later" requirement — a
228
+ // warn WITHOUT the schema would fail this assertion.
229
+ const warned = logger.logged.join('\n');
230
+ for (const tool of UNADAPTABLE_TOOLS) {
231
+ expect(warned).toContain(`skipping tool '${tool.name}'`);
232
+ // The raw schema, serialized exactly as adaptMcpTools emits it, must appear in the warn.
233
+ expect(warned).toContain(JSON.stringify(tool.inputSchema));
234
+ }
235
+ // And the reason fragments are present in the warnings too.
236
+ expect(warned).toMatch(/\$ref/);
237
+ expect(warned).toMatch(/union 'type'/);
238
+ });
239
+
240
+ test('an adapted tool executes end-to-end against the real server', async () => {
241
+ // Result-matcher-driven: extract the adapted `echo` tool inside the success satisfier (where
242
+ // its presence is asserted), then drive its execute callback — which round-trips through
243
+ // callMcpTool to the real server — with another matcher.
244
+ let echoExecute: ((args: unknown) => Promise<Result<unknown>>) | undefined;
245
+ expect(await adaptMcpTools(session)).toSucceedAndSatisfy((result) => {
246
+ const echo = result.tools.find((t) => t.config.name === 'echo');
247
+ expect(echo).toBeDefined();
248
+ echoExecute = echo?.execute;
249
+ });
250
+ expect(echoExecute).toBeDefined();
251
+ expect(await echoExecute?.({ msg: 'roundtrip' })).toSucceedWith('echo: {"msg":"roundtrip"}');
252
+ });
253
+ });
254
+ });