forked from clerk/mcp-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
544 lines (499 loc) · 16.5 KB
/
client.ts
File metadata and controls
544 lines (499 loc) · 16.5 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import { randomUUID } from "node:crypto";
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import type { OAuthClientInformationFull } from "@modelcontextprotocol/sdk/shared/auth.js";
const CODE_VERIFIER_PREFIX = "pkce_verifier_";
const STATE_PREFIX = "state_";
const SESSION_PREFIX = "session_";
export type JsonSerializable =
| null
| undefined
| boolean
| number
| string
| JsonSerializable[]
| { [key: string]: JsonSerializable };
export interface McpClientStore {
write: (key: string, value: JsonSerializable) => Promise<void>;
read: (key: string) => Promise<JsonSerializable>;
}
/**
* This function is used to complete the OAuth flow. It is used in the OAuth
* callback route to complete the OAuth flow given a state and auth code.
*/
export async function completeAuthWithCode({
state,
code,
store,
}: {
/**
* The authorization code returned from the auth provider via querystring.
* @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1
*/
code: string;
/**
* The state returned from the auth provider via querystring.
* @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1
*/
state: string;
/**
* A persistent store for auth data
* @see https://github.com/clerk/mcp-tools?tab=readme-ov-file#stores
*/
store: McpClientStore;
}) {
const sessionId = await store.read(`${STATE_PREFIX}${state}`);
if (!sessionId || typeof sessionId !== "string") {
throw new Error(
`No session id associated with state "${state}" found in the store`
);
}
const { transport } = await getClientBySessionId({
sessionId,
store,
state,
});
await transport.finishAuth(code);
// Read the updated client data AFTER finishAuth (which saves tokens)
const updatedClientData = await getClientData(sessionId, store);
// write to the store that the auth is complete
await store.write(`${SESSION_PREFIX}${sessionId}`, {
...updatedClientData,
authComplete: true,
});
return { transport, sessionId };
}
/**
* Given a client ID and a store, retrieves the client details and returns a
* transport and MCP client configured with an auth provider.
*/
export async function getClientBySessionId({
sessionId,
store,
state,
}: {
/**
* The session id to retrieve the client details for
*/
sessionId: string;
/**
* A persistent store for auth data
* @see https://github.com/clerk/mcp-tools?tab=readme-ov-file#stores
*/
store: McpClientStore;
/**
* If using this function in the OAuth callback route, pass in the state to
* ensure that PKCE can run correctly.
*/
state?: string;
}) {
const client = await getClientData(sessionId, store);
const authProvider: OAuthClientProvider = {
redirectUrl: client.oauthRedirectUrl,
clientMetadata: {
redirect_uris: [client.oauthRedirectUrl],
},
clientInformation: () => ({
client_id: client.clientId!,
client_secret: client.clientSecret!,
}),
saveClientInformation: async (newInfo: OAuthClientInformationFull) => {
await store.write(`${SESSION_PREFIX}${sessionId}`, {
...client,
...newInfo,
});
},
tokens: () => {
if (!client.accessToken) return undefined;
return { access_token: client.accessToken, token_type: "Bearer" };
},
saveTokens: async ({ access_token, refresh_token }) => {
await store.write(`${SESSION_PREFIX}${sessionId}`, {
...client,
accessToken: access_token,
refreshToken: refresh_token,
});
await store.read(`${SESSION_PREFIX}${sessionId}`);
return void 0;
},
redirectToAuthorization: unexpectedFunctionCall(
"redirectToAuthorization",
"getting an existing client"
),
saveCodeVerifier: unexpectedFunctionCall(
"saveCodeVerifier",
"getting an existing client"
),
codeVerifier: async (): Promise<string> => {
if (!state) {
throw new Error(
"The state argument is required to retrieve a code verifier for an already initialized client"
);
}
const storedVerifier = await store.read(
`${CODE_VERIFIER_PREFIX}${state}`
);
if (!storedVerifier || typeof storedVerifier !== "string") {
throw new Error(
`No code verifier found for state "${state}" in the store`
);
}
return storedVerifier;
},
};
return createReturnValue(client, authProvider, sessionId);
}
// Return type for known credentials and dynamically registered clients
export interface McpClientReturnType {
/**
* Represents a session associated with the connected MCP service endpoint.
*/
sessionId: string;
/**
* Calling this function will initialize a connect to the MCP service.
*/
connect: () => void;
/**
* Lower level primitive, likely not necessary for use
* @see https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/streamableHttp.ts#L119
*/
transport: StreamableHTTPClientTransport;
/**
* Lower level primitive, likely not necessary for use
* @see https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/index.ts#L81
*/
client: Client;
/**
* Lower level primitive, likely not necessary for use
* @see https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/auth.ts#L13
*/
authProvider: OAuthClientProvider;
}
export interface CreateKnownCredentialsMcpClientParams {
/**
* OAuth client id, expected to be collected via user input
*/
clientId: string;
/**
* OAuth client secret, expected to be collected via user input
*/
clientSecret: string;
/**
* The endpoint of the MCP service, expected to be collected via user input
*/
mcpEndpoint: string;
/**
* OAuth redirect URL - after the user consents, this route will get
* back the authorization code and state.
*/
oauthRedirectUrl: string;
/**
* OAuth scopes that you'd like to request access to
*/
oauthScopes?: string;
/**
* Name passed to the client created by the MCP SDK
* @see https://github.com/modelcontextprotocol/typescript-sdk?tab=readme-ov-file#writing-mcp-clients
*/
mcpClientName: string;
/**
* Version number passed to the client created by the MCP SDK
* @see https://github.com/modelcontextprotocol/typescript-sdk?tab=readme-ov-file#writing-mcp-clients
*/
mcpClientVersion: string;
/**
* A function that, when called with a url, will redirect to the given url
*/
redirect: (url: string) => void;
/**
* A persistent store for auth data
* @see https://github.com/clerk/mcp-tools?tab=readme-ov-file#stores
*/
store: McpClientStore;
}
/**
* Creates a new MCP client and transport for the first time with a known
* client id and secret for an existing oauth client.
*/
export async function createKnownCredentialsMcpClient({
redirect,
store,
...client
}: CreateKnownCredentialsMcpClientParams): Promise<McpClientReturnType> {
const state = randomUUID();
const sessionId = randomUUID();
// associate state with session id
// in the oauth callback, we only have the state, and will need to get the
// client information, so we need this to resolve the session id
await store.write(`${STATE_PREFIX}${state}`, sessionId);
// persist all the client details to the store, we will need them to
// re-create the client later in the oauth callback and any mcp call endpoints
await store.write(
`${SESSION_PREFIX}${sessionId}`,
client as JsonSerializable
);
// there's some non-dry code between this and the dynamically registered
// client, but this is on purpose for flexibility and clarity.
const authProvider: OAuthClientProvider = {
redirectUrl: client.oauthRedirectUrl,
clientMetadata: {
redirect_uris: [client.oauthRedirectUrl],
scope: client.oauthScopes,
},
state: () => state,
clientInformation: () => ({
client_id: client.clientId,
client_secret: client.clientSecret,
}),
// only should be used for dynamic client registration
saveClientInformation: unexpectedFunctionCall(
"saveClientInformation",
"initializing a known credentials client"
),
// it's impossible that we have an access token at this point, so we always
// return undefined
tokens: () => undefined,
// called in the oauth callback route
saveTokens: unexpectedFunctionCall(
"saveTokens",
"initializing a known credentials client"
),
redirectToAuthorization: (url) => {
redirect(url.toString());
},
saveCodeVerifier: async (verifier: string) => {
await store.write(`${CODE_VERIFIER_PREFIX}${state}`, verifier);
},
// called in the oauth callback route
codeVerifier: unexpectedFunctionCall(
"codeVerifier",
"initializing a known credentials client"
),
};
return createReturnValue(client, authProvider, sessionId);
}
export interface CreateDynamicallyRegisteredMcpClientParams {
/**
* The endpoint of the MCP service, expected to be collected via user input
*/
mcpEndpoint: string;
/**
* OAuth redirect URL - after the user consents, this route will get
* back the authorization code and state.
*/
oauthRedirectUrl: string;
/**
* The name of the OAuth client to be created with the authorization server
*/
oauthClientName?: string;
/**
* The URI of the OAuth client to be created with the authorization server
*/
oauthClientUri?: string;
/**
* OAuth scopes that you'd like to request access to
*/
oauthScopes?: string;
/**
* Whether the OAuth client is public or confidential
* @see https://datatracker.ietf.org/doc/html/rfc6749#section-2.1
*/
oauthPublicClient?: boolean;
/**
* Name passed to the client created by the MCP SDK
* @see https://github.com/modelcontextprotocol/typescript-sdk?tab=readme-ov-file#writing-mcp-clients
*/
mcpClientName: string;
/**
* Version number passed to the client created by the MCP SDK
* @see https://github.com/modelcontextprotocol/typescript-sdk?tab=readme-ov-file#writing-mcp-clients
*/
mcpClientVersion: string;
/**
* A function that, when called with a url, will redirect to the given url
*/
redirect: (url: string) => void;
/**
* A persistent store for auth data
* @see https://github.com/clerk/mcp-tools?tab=readme-ov-file#stores
*/
store: McpClientStore;
}
interface DynamicallyRegisteredClient
extends Omit<
CreateDynamicallyRegisteredMcpClientParams,
"store" | "redirect"
> {
clientId?: string;
clientSecret?: string;
}
/**
* Creates a new MCP client and transport for the first time that is assumed
* to need to be dynamically registered with an authorization server.
*/
export async function createDynamicallyRegisteredMcpClient({
redirect,
store,
...clientParams
}: CreateDynamicallyRegisteredMcpClientParams): Promise<McpClientReturnType> {
const state = randomUUID();
const sessionId = randomUUID();
// this is our in-memory client object, we will update it with the client id
// and secret after dynamic registration is complete
let client = {
...clientParams,
clientId: undefined as string | undefined,
clientSecret: undefined as string | undefined,
};
// associate state with session id
// in the oauth callback, we only have the state, and will need to get the
// client information, so we need this to resolve the session id
await store.write(`${STATE_PREFIX}${state}`, sessionId);
// persist all the client details to the store, we will need them to
// re-create the client later in the oauth callback and any mcp call endpoints
await store.write(`${SESSION_PREFIX}${sessionId}`, client);
const authProvider: OAuthClientProvider = {
redirectUrl: client.oauthRedirectUrl,
// this information is used to create an oauth client via dynamic client
// registration
clientMetadata: {
redirect_uris: [client.oauthRedirectUrl],
client_name: client.oauthClientName || client.mcpClientName,
client_uri: client.oauthClientUri,
scope: client.oauthScopes,
token_endpoint_auth_method: client.oauthPublicClient ? "none" : undefined,
},
state: () => state,
// this is called initially to see if there's an existing oauth client. if
// it returns undefined, the MCP SDK assumes that dynamic registration is
// needed. If dynamic registration is complete, we will have stored the
// oauth client credentials and will return them here, which the MCP SDK
// uses to construct the authorization url with the client id.
clientInformation: () => {
if (!client.clientId) {
return undefined;
}
return {
client_id: client.clientId,
client_secret: client.clientSecret,
};
},
// this is called after a new oauth client is created, so we now have a
// client id and secret
saveClientInformation: async (newInfo: OAuthClientInformationFull) => {
const newClientInfo = {
clientId: newInfo.client_id,
clientSecret: newInfo.client_secret,
};
// update the in-memory client object with the new client id and secret
client = { ...client, ...newClientInfo };
// persist the updated client object to the store
await store.write(`${SESSION_PREFIX}${sessionId}`, client);
},
// it's impossible that we have an access token at this point, so we always
// return undefined
tokens: () => undefined,
// called in the oauth callback route
saveTokens: async ({ access_token, refresh_token }) => {
await store.write(`${SESSION_PREFIX}${sessionId}`, {
...client,
accessToken: access_token,
refreshToken: refresh_token,
});
},
redirectToAuthorization: (url) => {
redirect(url.toString());
},
// since the code verifier is saved before the client is registered, we
// store it using the state as the key
saveCodeVerifier: async (verifier: string) => {
await store.write(`${CODE_VERIFIER_PREFIX}${state}`, verifier);
},
// called in the oauth callback route
codeVerifier: unexpectedFunctionCall(
"codeVerifier",
"initializing a dynamically registered client"
),
};
return createReturnValue(client, authProvider, sessionId);
}
/**
* Both known credentials and dynamically registered clients return the same
* values, so we abstract the common code here.
*/
function createReturnValue(
client: ClientData,
authProvider: OAuthClientProvider,
sessionId: string
) {
const transport = new StreamableHTTPClientTransport(
new URL(client.mcpEndpoint),
{ authProvider }
);
const mcpClient = new Client({
name: client.mcpClientName,
version: client.mcpClientVersion,
});
return {
sessionId,
connect: _connect.bind(null, mcpClient, transport),
transport,
client: mcpClient,
clientData: client,
authProvider,
};
}
/**
* A convenience function to connect the client with the provided transport.
*/
function _connect(client: Client, transport: StreamableHTTPClientTransport) {
return client.connect(transport);
}
/**
* The MCP SDK is designed as if the same AuthProvider can be stored in memory
* and used across multiple different routes, but in production code this isn't
* realistic. We know that during certain phases of the auth flow, certain
* methods should not be called, so we use this function to throw a nice clear
* error if they are.
*/
function unexpectedFunctionCall(name: string, phase: string) {
return () => {
throw new Error(
`Unexpected call to AuthProvider method "${name}" when ${phase}.`
);
};
}
/**
* The data that is stored in the store for a mcp client.
*/
export interface ClientData {
oauthRedirectUrl: string;
mcpEndpoint: string;
mcpClientName: string;
mcpClientVersion: string;
clientId?: string;
clientSecret?: string;
accessToken?: string;
refreshToken?: string;
authComplete?: boolean;
oauthClientName?: string;
oauthClientUri?: string;
oauthScopes?: string;
oauthPublicClient?: boolean;
}
/**
* Handles typing for reading client data our of the store by session id.
*/
async function getClientData(sessionId: string, store: McpClientStore) {
const clientData = await store.read(`${SESSION_PREFIX}${sessionId}`);
if (
!clientData ||
typeof clientData !== "object" ||
clientData === null ||
Array.isArray(clientData)
) {
throw new Error(`Session with ID "${sessionId}" not found in store`);
}
return clientData as unknown as ClientData;
}