-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathindex.ts
More file actions
218 lines (185 loc) · 6.42 KB
/
index.ts
File metadata and controls
218 lines (185 loc) · 6.42 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
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import readline from 'readline/promises';
import Anthropic from '@anthropic-ai/sdk';
import { Client, StdioClientTransport } from '@modelcontextprotocol/client';
const ANTHROPIC_MODEL = 'claude-sonnet-4-5';
interface ServerConfig {
command: string;
args?: string[];
env?: Record<string, string>;
}
interface ServersConfig {
mcpServers: Record<string, ServerConfig>;
}
class MultiServerClient {
private servers: Map<string, Client> = new Map();
private toolToServer: Map<string, { serverName: string; originalName: string }> = new Map();
private _anthropic: Anthropic | null = null;
private tools: Anthropic.Tool[] = [];
private get anthropic(): Anthropic {
return this._anthropic ??= new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
}
async connectToServers(configPath: string) {
const raw = readFileSync(resolve(configPath), 'utf-8');
const config: ServersConfig = JSON.parse(raw);
for (const [name, serverConfig] of Object.entries(config.mcpServers)) {
console.log(`Connecting to server: ${name}...`);
try {
const transport = new StdioClientTransport({
command: serverConfig.command,
args: serverConfig.args,
env: serverConfig.env
? { ...process.env as Record<string, string>, ...serverConfig.env }
: undefined,
});
const client = new Client({ name: `multi-server-client-${name}`, version: '1.0.0' });
await client.connect(transport);
this.servers.set(name, client);
// Discover tools from this server
const toolsResult = await client.listTools();
for (const tool of toolsResult.tools) {
const prefixedName = `${name}__${tool.name}`;
if (this.toolToServer.has(prefixedName)) {
console.warn(
` Warning: tool "${tool.name}" from server "${name}" collides with an existing tool.`
);
}
this.toolToServer.set(prefixedName, { serverName: name, originalName: tool.name });
this.tools.push({
name: prefixedName,
description: `[${name}] ${tool.description ?? ''}`,
input_schema: tool.inputSchema as Anthropic.Tool.InputSchema,
});
}
console.log(
` Connected to ${name} with tools: ${toolsResult.tools.map((t) => t.name).join(', ')}`
);
} catch (e) {
console.error(` Failed to connect to ${name}:`, e);
throw e;
}
}
console.log(`\nTotal tools available: ${this.tools.length}`);
}
async processQuery(query: string) {
const messages: Anthropic.MessageParam[] = [{ role: 'user', content: query }];
// Agentic loop: keep processing until the model stops issuing tool calls
let response = await this.anthropic.messages.create({
model: ANTHROPIC_MODEL,
max_tokens: 1000,
messages,
tools: this.tools,
});
const finalText: string[] = [];
while (response.stop_reason === 'tool_use') {
const assistantContent = response.content;
messages.push({ role: 'assistant', content: assistantContent });
const toolResults: Anthropic.ToolResultBlockParam[] = [];
for (const block of assistantContent) {
if (block.type === 'text') {
finalText.push(block.text);
} else if (block.type === 'tool_use') {
const mapping = this.toolToServer.get(block.name);
if (!mapping) {
toolResults.push({
type: 'tool_result',
tool_use_id: block.id,
content: `Error: unknown tool "${block.name}"`,
is_error: true,
});
continue;
}
const { serverName, originalName } = mapping;
const client = this.servers.get(serverName)!;
console.log(` [Calling ${originalName} on server "${serverName}"]`);
try {
const result = await client.callTool({
name: originalName,
arguments: block.input as Record<string, unknown> | undefined,
});
const resultText = result.content
.filter((c) => c.type === 'text')
.map((c) => c.text)
.join('\n');
toolResults.push({
type: 'tool_result',
tool_use_id: block.id,
content: resultText,
});
} catch (e) {
toolResults.push({
type: 'tool_result',
tool_use_id: block.id,
content: `Error executing tool: ${e}`,
is_error: true,
});
}
}
}
messages.push({ role: 'user', content: toolResults });
response = await this.anthropic.messages.create({
model: ANTHROPIC_MODEL,
max_tokens: 1000,
messages,
tools: this.tools,
});
}
// Collect any remaining text from the final response
for (const block of response.content) {
if (block.type === 'text') {
finalText.push(block.text);
}
}
return finalText.join('\n');
}
async chatLoop() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
try {
console.log('\nMulti-Server MCP Client Started!');
console.log('Type your queries or "quit" to exit.\n');
while (true) {
const message = await rl.question('Query: ');
if (message.toLowerCase() === 'quit') {
break;
}
const response = await this.processQuery(message);
console.log('\n' + response + '\n');
}
} finally {
rl.close();
}
}
async cleanup() {
for (const [name, client] of this.servers) {
console.log(`Disconnecting from ${name}...`);
await client.close();
}
}
}
async function main() {
const configPath = process.argv[2] ?? 'servers.json';
const mcpClient = new MultiServerClient();
try {
await mcpClient.connectToServers(configPath);
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
console.log(
'\nNo ANTHROPIC_API_KEY found. To chat with these tools via Claude, set your API key:'
+ '\n export ANTHROPIC_API_KEY=your-api-key-here'
);
return;
}
await mcpClient.chatLoop();
} catch (e) {
console.error('Error:', e);
process.exit(1);
} finally {
await mcpClient.cleanup();
process.exit(0);
}
}
main();