@mcp-ts/sdk 1.0.0
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/LICENSE +21 -0
- package/README.md +297 -0
- package/dist/adapters/agui-adapter.d.mts +119 -0
- package/dist/adapters/agui-adapter.d.ts +119 -0
- package/dist/adapters/agui-adapter.js +109 -0
- package/dist/adapters/agui-adapter.js.map +1 -0
- package/dist/adapters/agui-adapter.mjs +107 -0
- package/dist/adapters/agui-adapter.mjs.map +1 -0
- package/dist/adapters/agui-middleware.d.mts +171 -0
- package/dist/adapters/agui-middleware.d.ts +171 -0
- package/dist/adapters/agui-middleware.js +429 -0
- package/dist/adapters/agui-middleware.js.map +1 -0
- package/dist/adapters/agui-middleware.mjs +417 -0
- package/dist/adapters/agui-middleware.mjs.map +1 -0
- package/dist/adapters/ai-adapter.d.mts +38 -0
- package/dist/adapters/ai-adapter.d.ts +38 -0
- package/dist/adapters/ai-adapter.js +82 -0
- package/dist/adapters/ai-adapter.js.map +1 -0
- package/dist/adapters/ai-adapter.mjs +80 -0
- package/dist/adapters/ai-adapter.mjs.map +1 -0
- package/dist/adapters/langchain-adapter.d.mts +46 -0
- package/dist/adapters/langchain-adapter.d.ts +46 -0
- package/dist/adapters/langchain-adapter.js +102 -0
- package/dist/adapters/langchain-adapter.js.map +1 -0
- package/dist/adapters/langchain-adapter.mjs +100 -0
- package/dist/adapters/langchain-adapter.mjs.map +1 -0
- package/dist/adapters/mastra-adapter.d.mts +49 -0
- package/dist/adapters/mastra-adapter.d.ts +49 -0
- package/dist/adapters/mastra-adapter.js +95 -0
- package/dist/adapters/mastra-adapter.js.map +1 -0
- package/dist/adapters/mastra-adapter.mjs +93 -0
- package/dist/adapters/mastra-adapter.mjs.map +1 -0
- package/dist/client/index.d.mts +119 -0
- package/dist/client/index.d.ts +119 -0
- package/dist/client/index.js +225 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/index.mjs +223 -0
- package/dist/client/index.mjs.map +1 -0
- package/dist/client/react.d.mts +151 -0
- package/dist/client/react.d.ts +151 -0
- package/dist/client/react.js +492 -0
- package/dist/client/react.js.map +1 -0
- package/dist/client/react.mjs +489 -0
- package/dist/client/react.mjs.map +1 -0
- package/dist/client/vue.d.mts +157 -0
- package/dist/client/vue.d.ts +157 -0
- package/dist/client/vue.js +474 -0
- package/dist/client/vue.js.map +1 -0
- package/dist/client/vue.mjs +471 -0
- package/dist/client/vue.mjs.map +1 -0
- package/dist/events-BP6WyRNh.d.mts +110 -0
- package/dist/events-BP6WyRNh.d.ts +110 -0
- package/dist/index.d.mts +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +2784 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2723 -0
- package/dist/index.mjs.map +1 -0
- package/dist/multi-session-client-BOFgPypS.d.ts +389 -0
- package/dist/multi-session-client-DMF3ED2O.d.mts +389 -0
- package/dist/server/index.d.mts +269 -0
- package/dist/server/index.d.ts +269 -0
- package/dist/server/index.js +2444 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/index.mjs +2414 -0
- package/dist/server/index.mjs.map +1 -0
- package/dist/shared/index.d.mts +24 -0
- package/dist/shared/index.d.ts +24 -0
- package/dist/shared/index.js +223 -0
- package/dist/shared/index.js.map +1 -0
- package/dist/shared/index.mjs +190 -0
- package/dist/shared/index.mjs.map +1 -0
- package/dist/types-SbDlA2VX.d.mts +153 -0
- package/dist/types-SbDlA2VX.d.ts +153 -0
- package/dist/utils-0qmYrqoa.d.mts +92 -0
- package/dist/utils-0qmYrqoa.d.ts +92 -0
- package/package.json +165 -0
- package/src/adapters/agui-adapter.ts +210 -0
- package/src/adapters/agui-middleware.ts +512 -0
- package/src/adapters/ai-adapter.ts +115 -0
- package/src/adapters/langchain-adapter.ts +127 -0
- package/src/adapters/mastra-adapter.ts +126 -0
- package/src/client/core/sse-client.ts +340 -0
- package/src/client/index.ts +26 -0
- package/src/client/react/index.ts +10 -0
- package/src/client/react/useMcp.ts +558 -0
- package/src/client/vue/index.ts +10 -0
- package/src/client/vue/useMcp.ts +542 -0
- package/src/index.ts +11 -0
- package/src/server/handlers/nextjs-handler.ts +216 -0
- package/src/server/handlers/sse-handler.ts +699 -0
- package/src/server/index.ts +57 -0
- package/src/server/mcp/multi-session-client.ts +132 -0
- package/src/server/mcp/oauth-client.ts +1168 -0
- package/src/server/mcp/storage-oauth-provider.ts +239 -0
- package/src/server/storage/file-backend.ts +169 -0
- package/src/server/storage/index.ts +115 -0
- package/src/server/storage/memory-backend.ts +132 -0
- package/src/server/storage/redis-backend.ts +210 -0
- package/src/server/storage/redis.ts +160 -0
- package/src/server/storage/types.ts +109 -0
- package/src/shared/constants.ts +29 -0
- package/src/shared/errors.ts +133 -0
- package/src/shared/events.ts +166 -0
- package/src/shared/index.ts +70 -0
- package/src/shared/types.ts +274 -0
- package/src/shared/utils.ts +16 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { MCPClient } from '../server/mcp/oauth-client';
|
|
2
|
+
import { MultiSessionClient } from '../server/mcp/multi-session-client';
|
|
3
|
+
import type { DynamicStructuredTool, StructuredTool } from '@langchain/core/tools';
|
|
4
|
+
import type { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
export interface LangChainAdapterOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Prefix for tool names to avoid collision with other tools.
|
|
9
|
+
* Defaults to the client's serverId.
|
|
10
|
+
*/
|
|
11
|
+
prefix?: string;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Whether to simplify error messages returned to the LLM.
|
|
15
|
+
* If true, returns "Error: <message>" string instead of throwing.
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
simplifyErrors?: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Adapter to use MCP tools within LangChain/LangGraph agents.
|
|
23
|
+
*/
|
|
24
|
+
export class LangChainAdapter {
|
|
25
|
+
private DynamicStructuredTool: typeof DynamicStructuredTool | undefined;
|
|
26
|
+
private z: typeof z | undefined;
|
|
27
|
+
|
|
28
|
+
constructor(
|
|
29
|
+
private client: MCPClient | MultiSessionClient,
|
|
30
|
+
private options: LangChainAdapterOptions = {}
|
|
31
|
+
) { }
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Lazy-loads LangChain and Zod dependencies
|
|
35
|
+
*/
|
|
36
|
+
private async ensureDependencies() {
|
|
37
|
+
if (!this.DynamicStructuredTool) {
|
|
38
|
+
try {
|
|
39
|
+
const langchain = await import('@langchain/core/tools');
|
|
40
|
+
this.DynamicStructuredTool = langchain.DynamicStructuredTool;
|
|
41
|
+
|
|
42
|
+
const zod = await import('zod');
|
|
43
|
+
this.z = zod.z;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
'LangChain dependencies not installed. Install with:\n' +
|
|
47
|
+
' npm install @langchain/core zod'
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private async transformTools(client: MCPClient): Promise<StructuredTool[]> {
|
|
54
|
+
if (!client.isConnected()) {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
await this.ensureDependencies();
|
|
59
|
+
|
|
60
|
+
const result = await client.listTools();
|
|
61
|
+
const prefix = this.options.prefix ?? client.getServerId() ?? 'mcp';
|
|
62
|
+
|
|
63
|
+
return result.tools.map((tool) => {
|
|
64
|
+
// In a real implementation, you would use a library like 'json-schema-to-zod'
|
|
65
|
+
const schema = this.jsonSchemaToZod(tool.inputSchema);
|
|
66
|
+
|
|
67
|
+
return new this.DynamicStructuredTool!({
|
|
68
|
+
name: `${prefix}_${tool.name}`,
|
|
69
|
+
description: tool.description || `Tool ${tool.name}`,
|
|
70
|
+
schema: schema,
|
|
71
|
+
func: async (args: any) => {
|
|
72
|
+
try {
|
|
73
|
+
return await client.callTool(tool.name, args);
|
|
74
|
+
} catch (error: any) {
|
|
75
|
+
if (this.options.simplifyErrors) {
|
|
76
|
+
return `Error: ${error.message}`;
|
|
77
|
+
}
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private jsonSchemaToZod(schema: any): z.ZodType<any> {
|
|
86
|
+
try {
|
|
87
|
+
const { parseSchema } = require('json-schema-to-zod');
|
|
88
|
+
const zodSchemaString = parseSchema(schema);
|
|
89
|
+
// eslint-disable-next-line
|
|
90
|
+
return new Function('z', 'return ' + zodSchemaString)(this.z);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
// Fallback: Accept any object if conversion fails
|
|
93
|
+
console.warn('[LangChainAdapter] Failed to convert JSON Schema to Zod, using fallback:', error);
|
|
94
|
+
return this.z!.record(this.z!.any()).optional().describe("Dynamic Input");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Fetches tools from the MCP server and converts them to LangChain StructuredTools.
|
|
100
|
+
*/
|
|
101
|
+
async getTools(): Promise<StructuredTool[]> {
|
|
102
|
+
// Use duck typing instead of instanceof to handle module bundling issues
|
|
103
|
+
const isMultiSession = typeof (this.client as any).getClients === 'function';
|
|
104
|
+
const clients = isMultiSession
|
|
105
|
+
? (this.client as MultiSessionClient).getClients()
|
|
106
|
+
: [this.client as MCPClient];
|
|
107
|
+
|
|
108
|
+
const results = await Promise.all(
|
|
109
|
+
clients.map(async (client) => {
|
|
110
|
+
try {
|
|
111
|
+
return await this.transformTools(client);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
console.error(`[LangChainAdapter] Failed to fetch tools from ${client.getServerId()}:`, error);
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
})
|
|
117
|
+
);
|
|
118
|
+
return results.flat();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Convenience static method to fetch tools in a single line.
|
|
123
|
+
*/
|
|
124
|
+
static async getTools(client: MCPClient | MultiSessionClient, options: LangChainAdapterOptions = {}): Promise<StructuredTool[]> {
|
|
125
|
+
return new LangChainAdapter(client, options).getTools();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { MCPClient } from '../server/mcp/oauth-client';
|
|
2
|
+
import { MultiSessionClient } from '../server/mcp/multi-session-client';
|
|
3
|
+
import type { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
export interface MastraAdapterOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Prefix for tool names to avoid collision with other tools.
|
|
8
|
+
* Defaults to the client's serverId.
|
|
9
|
+
*/
|
|
10
|
+
prefix?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Interface definition for a Mastra tool since we might not have the SDK installed.
|
|
15
|
+
* Based on Mastra documentation.
|
|
16
|
+
*/
|
|
17
|
+
export interface MastraTool {
|
|
18
|
+
id: string;
|
|
19
|
+
description: string;
|
|
20
|
+
inputSchema: z.ZodType<any>;
|
|
21
|
+
execute: (args: any) => Promise<any>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Adapter to use MCP tools within Mastra agents.
|
|
26
|
+
*/
|
|
27
|
+
export class MastraAdapter {
|
|
28
|
+
private z: typeof z | undefined;
|
|
29
|
+
|
|
30
|
+
constructor(
|
|
31
|
+
private client: MCPClient | MultiSessionClient,
|
|
32
|
+
private options: MastraAdapterOptions = {}
|
|
33
|
+
) { }
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Lazy-loads Zod dependency
|
|
37
|
+
*/
|
|
38
|
+
private async ensureZod() {
|
|
39
|
+
if (!this.z) {
|
|
40
|
+
try {
|
|
41
|
+
const zod = await import('zod');
|
|
42
|
+
this.z = zod.z;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
'zod is not installed. Install with:\n' +
|
|
46
|
+
' npm install zod'
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
private async transformTools(client: MCPClient): Promise<Record<string, MastraTool>> {
|
|
55
|
+
if (!client.isConnected()) {
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
await this.ensureZod();
|
|
60
|
+
|
|
61
|
+
const result = await client.listTools();
|
|
62
|
+
const prefix = this.options.prefix ?? client.getServerId() ?? 'mcp';
|
|
63
|
+
const tools: Record<string, MastraTool> = {};
|
|
64
|
+
|
|
65
|
+
for (const tool of result.tools) {
|
|
66
|
+
const toolName = `${prefix}_${tool.name}`;
|
|
67
|
+
|
|
68
|
+
// In a real implementation, you would use a library like 'json-schema-to-zod'
|
|
69
|
+
const schema = this.jsonSchemaToZod(tool.inputSchema);
|
|
70
|
+
|
|
71
|
+
tools[toolName] = {
|
|
72
|
+
id: toolName,
|
|
73
|
+
description: tool.description || `Tool ${tool.name}`,
|
|
74
|
+
inputSchema: schema,
|
|
75
|
+
execute: async (args: any) => {
|
|
76
|
+
return await client.callTool(tool.name, args);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return tools;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private jsonSchemaToZod(schema: any): z.ZodType<any> {
|
|
85
|
+
try {
|
|
86
|
+
const { parseSchema } = require('json-schema-to-zod');
|
|
87
|
+
const zodSchemaString = parseSchema(schema);
|
|
88
|
+
// eslint-disable-next-line
|
|
89
|
+
return new Function('z', 'return ' + zodSchemaString)(this.z);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
// Fallback: Accept any object if conversion fails
|
|
92
|
+
console.warn('[MastraAdapter] Failed to convert JSON Schema to Zod, using fallback:', error);
|
|
93
|
+
return this.z!.record(this.z!.any()).optional().describe("Dynamic Input");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Fetches tools from the MCP server and converts them to Mastra tools.
|
|
99
|
+
*/
|
|
100
|
+
async getTools(): Promise<Record<string, MastraTool>> {
|
|
101
|
+
// Use duck typing instead of instanceof to handle module bundling issues
|
|
102
|
+
const isMultiSession = typeof (this.client as any).getClients === 'function';
|
|
103
|
+
const clients = isMultiSession
|
|
104
|
+
? (this.client as MultiSessionClient).getClients()
|
|
105
|
+
: [this.client as MCPClient];
|
|
106
|
+
|
|
107
|
+
const results = await Promise.all(
|
|
108
|
+
clients.map(async (client) => {
|
|
109
|
+
try {
|
|
110
|
+
return await this.transformTools(client);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
console.error(`[MastraAdapter] Failed to fetch tools from ${client.getServerId()}:`, error);
|
|
113
|
+
return {};
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
);
|
|
117
|
+
return results.reduce((acc, tools) => ({ ...acc, ...tools }), {});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Convenience static method to fetch tools in a single line.
|
|
122
|
+
*/
|
|
123
|
+
static async getTools(client: MCPClient | MultiSessionClient, options: MastraAdapterOptions = {}): Promise<Record<string, MastraTool>> {
|
|
124
|
+
return new MastraAdapter(client, options).getTools();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSE Client for MCP Connections
|
|
3
|
+
* Browser-side client that connects to SSE endpoint
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { nanoid } from 'nanoid';
|
|
7
|
+
import type { McpConnectionEvent, McpObservabilityEvent } from '../../shared/events';
|
|
8
|
+
import type {
|
|
9
|
+
McpRpcRequest,
|
|
10
|
+
McpRpcResponse,
|
|
11
|
+
McpRpcMethod,
|
|
12
|
+
McpRpcParams,
|
|
13
|
+
ConnectParams,
|
|
14
|
+
SessionListResult,
|
|
15
|
+
ConnectResult,
|
|
16
|
+
DisconnectResult,
|
|
17
|
+
RestoreSessionResult,
|
|
18
|
+
FinishAuthResult,
|
|
19
|
+
ListToolsRpcResult,
|
|
20
|
+
ListPromptsResult,
|
|
21
|
+
ListResourcesResult,
|
|
22
|
+
} from '../../shared/types';
|
|
23
|
+
|
|
24
|
+
export interface SSEClientOptions {
|
|
25
|
+
/**
|
|
26
|
+
* SSE endpoint URL
|
|
27
|
+
*/
|
|
28
|
+
url: string;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* User/Client identifier
|
|
32
|
+
*/
|
|
33
|
+
identity: string;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Optional auth token
|
|
37
|
+
*/
|
|
38
|
+
authToken?: string;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Connection event callback
|
|
42
|
+
*/
|
|
43
|
+
onConnectionEvent?: (event: McpConnectionEvent) => void;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Observability event callback
|
|
47
|
+
*/
|
|
48
|
+
onObservabilityEvent?: (event: McpObservabilityEvent) => void;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Connection status callback
|
|
52
|
+
*/
|
|
53
|
+
onStatusChange?: (status: 'connecting' | 'connected' | 'disconnected' | 'error') => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* SSE Client for real-time MCP connection management
|
|
58
|
+
*/
|
|
59
|
+
export class SSEClient {
|
|
60
|
+
private eventSource: EventSource | null = null;
|
|
61
|
+
private pendingRequests: Map<
|
|
62
|
+
string,
|
|
63
|
+
{ resolve: (value: unknown) => void; reject: (error: Error) => void }
|
|
64
|
+
> = new Map();
|
|
65
|
+
private reconnectAttempts: number = 0;
|
|
66
|
+
private maxReconnectAttempts: number = 5;
|
|
67
|
+
private reconnectDelay: number = 1000;
|
|
68
|
+
private isManuallyDisconnected: boolean = false;
|
|
69
|
+
private connectionPromise: Promise<void> | null = null;
|
|
70
|
+
private connectionResolver: (() => void) | null = null;
|
|
71
|
+
|
|
72
|
+
constructor(private options: SSEClientOptions) { }
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Connect to SSE endpoint
|
|
76
|
+
*/
|
|
77
|
+
connect(): void {
|
|
78
|
+
if (this.eventSource) {
|
|
79
|
+
return; // Already connected
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
this.isManuallyDisconnected = false;
|
|
83
|
+
this.options.onStatusChange?.('connecting');
|
|
84
|
+
|
|
85
|
+
// Create connection promise
|
|
86
|
+
this.connectionPromise = new Promise((resolve) => {
|
|
87
|
+
this.connectionResolver = resolve;
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// Build URL with query params
|
|
91
|
+
// Handle both relative and absolute URLs
|
|
92
|
+
const url = new URL(this.options.url, typeof window !== 'undefined' ? window.location.origin : undefined);
|
|
93
|
+
url.searchParams.set('identity', this.options.identity);
|
|
94
|
+
if (this.options.authToken) {
|
|
95
|
+
url.searchParams.set('token', this.options.authToken);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Create EventSource
|
|
99
|
+
this.eventSource = new EventSource(url.toString());
|
|
100
|
+
|
|
101
|
+
// Handle connection open
|
|
102
|
+
this.eventSource.addEventListener('open', () => {
|
|
103
|
+
console.log('[SSEClient] Connected');
|
|
104
|
+
this.reconnectAttempts = 0;
|
|
105
|
+
this.options.onStatusChange?.('connected');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// Handle 'connected' event - server confirms manager is ready
|
|
109
|
+
this.eventSource.addEventListener('connected', (e: MessageEvent) => {
|
|
110
|
+
const data = JSON.parse(e.data);
|
|
111
|
+
console.log('[SSEClient] Server ready:', data);
|
|
112
|
+
|
|
113
|
+
// Resolve connection promise - now safe to send requests
|
|
114
|
+
if (this.connectionResolver) {
|
|
115
|
+
this.connectionResolver();
|
|
116
|
+
this.connectionResolver = null;
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// Handle 'connection' events (MCP connection state changes)
|
|
121
|
+
this.eventSource.addEventListener('connection', (e: MessageEvent) => {
|
|
122
|
+
const event: McpConnectionEvent = JSON.parse(e.data);
|
|
123
|
+
this.options.onConnectionEvent?.(event);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// Handle 'observability' events (debugging/logging)
|
|
127
|
+
this.eventSource.addEventListener('observability', (e: MessageEvent) => {
|
|
128
|
+
const event: McpObservabilityEvent = JSON.parse(e.data);
|
|
129
|
+
this.options.onObservabilityEvent?.(event);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// Handle 'rpc-response' events (RPC method responses)
|
|
133
|
+
this.eventSource.addEventListener('rpc-response', (e: MessageEvent) => {
|
|
134
|
+
const response: McpRpcResponse = JSON.parse(e.data);
|
|
135
|
+
this.handleRpcResponse(response);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// Handle errors
|
|
139
|
+
this.eventSource.addEventListener('error', () => {
|
|
140
|
+
console.error('[SSEClient] Connection error');
|
|
141
|
+
this.options.onStatusChange?.('error');
|
|
142
|
+
|
|
143
|
+
// Attempt reconnection
|
|
144
|
+
if (!this.isManuallyDisconnected && this.reconnectAttempts < this.maxReconnectAttempts) {
|
|
145
|
+
this.reconnectAttempts++;
|
|
146
|
+
console.log(`[SSEClient] Reconnecting (attempt ${this.reconnectAttempts})...`);
|
|
147
|
+
|
|
148
|
+
setTimeout(() => {
|
|
149
|
+
this.disconnect();
|
|
150
|
+
this.connect();
|
|
151
|
+
}, this.reconnectDelay * this.reconnectAttempts);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Disconnect from SSE endpoint
|
|
158
|
+
*/
|
|
159
|
+
disconnect(): void {
|
|
160
|
+
this.isManuallyDisconnected = true;
|
|
161
|
+
|
|
162
|
+
if (this.eventSource) {
|
|
163
|
+
this.eventSource.close();
|
|
164
|
+
this.eventSource = null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Reset connection promise
|
|
168
|
+
this.connectionPromise = null;
|
|
169
|
+
this.connectionResolver = null;
|
|
170
|
+
|
|
171
|
+
// Reject all pending requests with a specific error type
|
|
172
|
+
for (const [id, { reject }] of this.pendingRequests.entries()) {
|
|
173
|
+
const error = new Error('Connection closed');
|
|
174
|
+
error.name = 'ConnectionClosedError';
|
|
175
|
+
reject(error);
|
|
176
|
+
}
|
|
177
|
+
this.pendingRequests.clear();
|
|
178
|
+
|
|
179
|
+
this.options.onStatusChange?.('disconnected');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Send RPC request via SSE
|
|
184
|
+
* Note: SSE is unidirectional (server->client), so we need to send requests via POST
|
|
185
|
+
*/
|
|
186
|
+
private async sendRequest<T = unknown>(method: McpRpcMethod, params?: McpRpcParams): Promise<T> {
|
|
187
|
+
// Wait for connection to be fully established
|
|
188
|
+
if (this.connectionPromise) {
|
|
189
|
+
await this.connectionPromise;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Generate unique request ID using nanoid (e.g., "rpc_V1StGXR8_Z5jdHi")
|
|
193
|
+
const id = `rpc_${nanoid(10)}`;
|
|
194
|
+
|
|
195
|
+
const request: McpRpcRequest = {
|
|
196
|
+
id,
|
|
197
|
+
method,
|
|
198
|
+
params,
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
// Create promise for response
|
|
202
|
+
const promise = new Promise<T>((resolve, reject) => {
|
|
203
|
+
this.pendingRequests.set(id, { resolve: resolve as (value: unknown) => void, reject });
|
|
204
|
+
|
|
205
|
+
// Timeout after 30 seconds
|
|
206
|
+
setTimeout(() => {
|
|
207
|
+
if (this.pendingRequests.has(id)) {
|
|
208
|
+
this.pendingRequests.delete(id);
|
|
209
|
+
reject(new Error('Request timeout'));
|
|
210
|
+
}
|
|
211
|
+
}, 30000);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// Send request via POST to same endpoint
|
|
215
|
+
try {
|
|
216
|
+
// Handle both relative and absolute URLs
|
|
217
|
+
const url = new URL(this.options.url, typeof window !== 'undefined' ? window.location.origin : undefined);
|
|
218
|
+
url.searchParams.set('identity', this.options.identity);
|
|
219
|
+
|
|
220
|
+
await fetch(url.toString(), {
|
|
221
|
+
method: 'POST',
|
|
222
|
+
headers: {
|
|
223
|
+
'Content-Type': 'application/json',
|
|
224
|
+
...(this.options.authToken && { Authorization: `Bearer ${this.options.authToken}` }),
|
|
225
|
+
},
|
|
226
|
+
body: JSON.stringify(request),
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
this.pendingRequests.delete(id);
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return promise;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Handle RPC response
|
|
238
|
+
*/
|
|
239
|
+
private handleRpcResponse(response: McpRpcResponse): void {
|
|
240
|
+
const pending = this.pendingRequests.get(response.id);
|
|
241
|
+
|
|
242
|
+
if (pending) {
|
|
243
|
+
this.pendingRequests.delete(response.id);
|
|
244
|
+
|
|
245
|
+
if (response.error) {
|
|
246
|
+
pending.reject(new Error(response.error.message));
|
|
247
|
+
} else {
|
|
248
|
+
pending.resolve(response.result);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Get all user sessions
|
|
255
|
+
*/
|
|
256
|
+
async getSessions(): Promise<SessionListResult> {
|
|
257
|
+
return this.sendRequest<SessionListResult>('getSessions');
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Connect to an MCP server
|
|
262
|
+
*/
|
|
263
|
+
async connectToServer(params: ConnectParams): Promise<ConnectResult> {
|
|
264
|
+
return this.sendRequest<ConnectResult>('connect', params);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Disconnect from an MCP server
|
|
269
|
+
*/
|
|
270
|
+
async disconnectFromServer(sessionId: string): Promise<DisconnectResult> {
|
|
271
|
+
return this.sendRequest<DisconnectResult>('disconnect', { sessionId });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* List tools from a session
|
|
276
|
+
*/
|
|
277
|
+
async listTools(sessionId: string): Promise<ListToolsRpcResult> {
|
|
278
|
+
return this.sendRequest<ListToolsRpcResult>('listTools', { sessionId });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Call a tool
|
|
283
|
+
*/
|
|
284
|
+
async callTool(
|
|
285
|
+
sessionId: string,
|
|
286
|
+
toolName: string,
|
|
287
|
+
toolArgs: Record<string, unknown>
|
|
288
|
+
): Promise<unknown> {
|
|
289
|
+
return this.sendRequest('callTool', { sessionId, toolName, toolArgs });
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Refresh/validate a session
|
|
294
|
+
*/
|
|
295
|
+
async restoreSession(sessionId: string): Promise<RestoreSessionResult> {
|
|
296
|
+
return this.sendRequest<RestoreSessionResult>('restoreSession', { sessionId });
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Complete OAuth authorization
|
|
301
|
+
*/
|
|
302
|
+
async finishAuth(sessionId: string, code: string): Promise<FinishAuthResult> {
|
|
303
|
+
return this.sendRequest<FinishAuthResult>('finishAuth', { sessionId, code });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* List available prompts
|
|
308
|
+
*/
|
|
309
|
+
async listPrompts(sessionId: string): Promise<ListPromptsResult> {
|
|
310
|
+
return this.sendRequest<ListPromptsResult>('listPrompts', { sessionId });
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Get a specific prompt with arguments
|
|
315
|
+
*/
|
|
316
|
+
async getPrompt(sessionId: string, name: string, args?: Record<string, string>): Promise<unknown> {
|
|
317
|
+
return this.sendRequest('getPrompt', { sessionId, name, args });
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* List available resources
|
|
322
|
+
*/
|
|
323
|
+
async listResources(sessionId: string): Promise<ListResourcesResult> {
|
|
324
|
+
return this.sendRequest<ListResourcesResult>('listResources', { sessionId });
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Read a specific resource
|
|
329
|
+
*/
|
|
330
|
+
async readResource(sessionId: string, uri: string): Promise<unknown> {
|
|
331
|
+
return this.sendRequest('readResource', { sessionId, uri });
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Check if connected
|
|
336
|
+
*/
|
|
337
|
+
isConnected(): boolean {
|
|
338
|
+
return this.eventSource !== null && this.eventSource.readyState === EventSource.OPEN;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Redis Client Package
|
|
3
|
+
* Browser/React client-side exports for MCP connection management
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** SSE client for real-time connections */
|
|
7
|
+
export { SSEClient, type SSEClientOptions } from './core/sse-client';
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
/** Re-export shared types */
|
|
12
|
+
export type {
|
|
13
|
+
McpConnectionEvent,
|
|
14
|
+
McpConnectionState,
|
|
15
|
+
McpObservabilityEvent,
|
|
16
|
+
Emitter,
|
|
17
|
+
Disposable,
|
|
18
|
+
Event,
|
|
19
|
+
DisposableStore,
|
|
20
|
+
} from '../shared/events';
|
|
21
|
+
|
|
22
|
+
export type {
|
|
23
|
+
ToolInfo,
|
|
24
|
+
McpRpcRequest,
|
|
25
|
+
McpRpcResponse,
|
|
26
|
+
} from '../shared/types';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Redis Client Package - React
|
|
3
|
+
* React client-side exports for MCP connection management
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// React Hook
|
|
7
|
+
export { useMcp, type UseMcpOptions, type McpClient, type McpConnection } from './useMcp';
|
|
8
|
+
|
|
9
|
+
// Re-export shared types and client from main entry
|
|
10
|
+
export * from '../index';
|