-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmcp-connection.ts
More file actions
217 lines (202 loc) · 6.86 KB
/
Copy pathmcp-connection.ts
File metadata and controls
217 lines (202 loc) · 6.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// SSEClientTransport is deprecated upstream (SEP-2596) but intentionally
// supported here for legacy MCP servers that haven't migrated to Streamable HTTP.
import {
Client,
SSEClientTransport,
StreamableHTTPClientTransport,
} from '@modelcontextprotocol/client';
import { resolveAuth } from './auth/auth-resolver.js';
import type { MCPAuth } from './auth/auth-types.js';
import { makeElicitationRequestHandler } from './elicitation.js';
import { MCPConnectionError } from './errors.js';
import type { MCPProtocolNegotiation, MCPTransportKind } from './transport-types.js';
import type { ElicitationHandler } from './types.js';
import { PACKAGE_VERSION } from './version.js';
// Self-reported to every MCP server we connect to as `clientInfo`. The version
// is generated from package.json (scripts/gen-version.mjs) so it cannot drift.
const DEFAULT_CLIENT_INFO = {
name: '@openrouter/mcp',
version: PACKAGE_VERSION,
};
export interface ConnectOptions {
url: URL;
transport?: MCPTransportKind;
auth?: MCPAuth;
fetch?: typeof fetch;
clientInfo?: {
name: string;
version: string;
};
/**
* Streamable HTTP session id to resume.
*
* @deprecated Ignored by 2026-07-28 servers — protocol-level sessions are
* removed (SEP-2567). Still honoured on 2025-era connections.
*/
sessionId?: string;
onElicitation?: ElicitationHandler;
protocolNegotiation?: MCPProtocolNegotiation;
}
export interface MCPConnection {
client: Client;
transport: MCPTransportKind;
/**
* Session id reported by the transport, when there is one.
*
* @deprecated `undefined` on 2026-07-28 connections (SEP-2567) and on SSE,
* which never had a protocol-level session.
*/
sessionId?: string;
/**
* Register a callback for `tools/list_changed`. Settable after connect so the
* handle can wire it to its own `refresh()`. Replaces any prior handler.
*/
setToolListChangedHandler(handler: () => void): void;
close(): Promise<void>;
}
function buildStreamableHttp(options: ConnectOptions): StreamableHTTPClientTransport {
const { headers, authProvider } = resolveAuth(options.auth);
return new StreamableHTTPClientTransport(options.url, {
requestInit: {
headers,
},
...(authProvider !== undefined && {
authProvider,
}),
...(options.fetch !== undefined && {
fetch: options.fetch,
}),
...(options.sessionId !== undefined && {
sessionId: options.sessionId,
}),
});
}
function buildSse(options: ConnectOptions): SSEClientTransport {
const { headers, authProvider } = resolveAuth(options.auth);
return new SSEClientTransport(options.url, {
requestInit: {
headers,
},
...(authProvider !== undefined && {
authProvider,
}),
...(options.fetch !== undefined && {
fetch: options.fetch,
}),
});
}
interface MutableListChanged {
handler: (() => void) | undefined;
}
function makeClient(options: ConnectOptions, listChanged: MutableListChanged): Client {
const client = new Client(options.clientInfo ?? DEFAULT_CLIENT_INFO, {
capabilities: {
elicitation: {},
},
// The SDK defaults to 'legacy'; we default to 'auto' so callers reach both
// 2025-era and 2026-07-28 servers without configuring anything.
//
// `inputRequired` is deliberately left unset: its defaults (auto-fulfil on,
// 10 rounds) are what we want, and pinning them here would freeze values
// the SDK may tune.
versionNegotiation: {
mode: options.protocolNegotiation ?? 'auto',
},
});
// Method-name-first in SDK v2; spec methods supply their own schema. This one
// handler serves both protocol eras: on 2025-era connections the server sends
// `elicitation/create` directly, and on 2026-07-28 the multi-round-trip driver
// dispatches `input_required` through this same handler, then retries the
// original call with the collected `inputResponses`.
client.setRequestHandler(
'elicitation/create',
makeElicitationRequestHandler(options.onElicitation),
);
// Kept as a notification handler rather than `ClientOptions.listChanged`: the
// latter re-lists tools itself, duplicating the handle's own `refresh()` and
// its cache write. Notification handlers are era-transparent.
client.setNotificationHandler('notifications/tools/list_changed', () => {
listChanged.handler?.();
});
return client;
}
/**
* Connect a `Client` to the MCP server. Defaults to Streamable HTTP and falls
* back to SSE on connection failure (legacy servers), unless a transport is
* pinned explicitly. Auth, the elicitation handler, and the list_changed
* subscription are wired into the single connected client so they apply to
* discovery and every tool call.
*/
export async function connect(options: ConnectOptions): Promise<MCPConnection> {
const preferred = options.transport ?? 'streamableHttp';
const listChanged: MutableListChanged = {
handler: undefined,
};
if (preferred === 'sse') {
const client = makeClient(options, listChanged);
await client.connect(buildSse(options));
return wrap({
client,
transport: 'sse',
listChanged,
});
}
// Streamable HTTP, with SSE fallback when the transport wasn't pinned.
const client = makeClient(options, listChanged);
try {
const http = buildStreamableHttp(options);
await client.connect(http);
return wrap({
client,
transport: 'streamableHttp',
listChanged,
...(http.sessionId !== undefined && {
sessionId: http.sessionId,
}),
});
} catch (httpErr) {
if (options.transport === 'streamableHttp') {
throw new MCPConnectionError('Failed to connect over Streamable HTTP', {
cause: httpErr,
});
}
// Fall back to SSE on a fresh client (the failed one may be half-initialized).
// Note this also catches version-probe failures under `'auto'`: on HTTP a
// probe timeout is an outage, so the SSE attempt below will usually fail too
// and surface the combined error. Callers on flaky servers can skip the
// probe entirely with `protocolNegotiation: 'legacy'`.
const sseClient = makeClient(options, listChanged);
try {
await sseClient.connect(buildSse(options));
return wrap({
client: sseClient,
transport: 'sse',
listChanged,
});
} catch (sseErr) {
throw new MCPConnectionError('Failed to connect over Streamable HTTP and SSE', {
cause: sseErr,
});
}
}
}
interface WrapArgs {
client: Client;
transport: MCPTransportKind;
listChanged: MutableListChanged;
sessionId?: string;
}
function wrap(args: WrapArgs): MCPConnection {
const { client, transport, listChanged, sessionId } = args;
return {
client,
transport,
...(sessionId !== undefined && {
sessionId,
}),
setToolListChangedHandler: (handler: () => void) => {
listChanged.handler = handler;
},
close: () => client.close(),
};
}