-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmcp-server.ts
More file actions
389 lines (386 loc) · 12.4 KB
/
mcp-server.ts
File metadata and controls
389 lines (386 loc) · 12.4 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
/**
* MCP Server - Exposes context-connector tools to AI assistants.
*
* Implements the Model Context Protocol (MCP) to enable integration with:
* - Claude Desktop
* - Other MCP-compatible AI assistants
*
* The server exposes these tools:
* - `search`: Search across one or more indexes
* - `list_files`: List files in an index (when source available)
* - `read_file`: Read file contents (when source available)
*
* @module clients/mcp-server
* @see https://modelcontextprotocol.io/
*
* @example
* ```typescript
* import { runMCPServer } from "@augmentcode/context-connectors";
* import { FilesystemStore } from "@augmentcode/context-connectors/stores";
*
* // Serve all indexes in the store
* await runMCPServer({
* store: new FilesystemStore(),
* });
*
* // Serve specific indexes only
* await runMCPServer({
* store: new FilesystemStore(),
* indexNames: ["react", "docs"],
* });
* ```
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import type { IndexStoreReader } from "../stores/types.js";
import { MultiIndexRunner } from "./multi-index-runner.js";
import { buildClientUserAgent, type MCPClientInfo } from "../core/utils.js";
import {
SEARCH_DESCRIPTION,
LIST_FILES_DESCRIPTION,
READ_FILE_DESCRIPTION,
withIndexList,
} from "./tool-descriptions.js";
/**
* Configuration for the MCP server.
*/
export interface MCPServerConfig {
/** Store to load indexes from */
store: IndexStoreReader;
/**
* Index names to expose. If undefined, all indexes in the store are exposed.
*/
indexNames?: string[];
/**
* Disable file operations (list_files, read_file).
* When true, only search is available.
*/
searchOnly?: boolean;
/**
* Server name reported to MCP clients.
* @default "context-connectors"
*/
serverName?: string;
/**
* Server version reported to MCP clients.
* @default "0.1.0"
*/
version?: string;
/**
* Optional pre-initialized MultiIndexRunner to share across sessions.
* When provided, this runner is used instead of creating a new one.
* This is useful for HTTP servers to avoid redundant store.list() and
* store.loadSearch() calls for every session.
* @internal Used by mcp-http-server for session sharing optimization
*/
runner?: MultiIndexRunner;
}
/**
* Create an MCP server instance.
*
* Creates but does not start the server. Use `runMCPServer()` for
* the common case of running with stdio transport.
*
* @param config - Server configuration
* @returns Configured MCP Server instance
*
* @example
* ```typescript
* const server = await createMCPServer({
* store: new FilesystemStore(),
* });
*
* // Connect with custom transport
* await server.connect(myTransport);
* ```
*/
export async function createMCPServer(
config: MCPServerConfig
): Promise<Server> {
// Use provided runner if available (for HTTP session sharing),
// otherwise create a new one (for stdio server)
let runner: MultiIndexRunner;
if (config.runner) {
runner = config.runner;
} else {
// Build User-Agent for analytics tracking
const clientUserAgent = buildClientUserAgent("mcp");
runner = await MultiIndexRunner.create({
store: config.store,
indexNames: config.indexNames,
searchOnly: config.searchOnly,
clientUserAgent,
});
}
const { indexNames, indexes } = runner;
const searchOnly = !runner.hasFileOperations();
// Format index list for tool descriptions
const indexListStr = runner.getIndexListString();
// Create MCP server
const server = new Server(
{
name: config.serverName ?? "context-connectors",
version: config.version ?? "0.1.0",
},
{
capabilities: {
tools: {},
},
}
);
// Use the SDK's oninitialized callback to capture MCP client info
// This preserves the SDK's protocol version negotiation
// Note: When using a shared runner (HTTP sessions), this updates the runner
// for all sessions (last writer wins). This is intentional - we want to track
// the most recent client info for analytics.
server.oninitialized = () => {
const clientInfo = server.getClientVersion();
if (clientInfo) {
const mcpClientInfo: MCPClientInfo = {
name: clientInfo.name,
version: clientInfo.version,
};
const updatedUserAgent = buildClientUserAgent("mcp", mcpClientInfo);
runner.updateClientUserAgent(updatedUserAgent);
}
};
// Define tool type for type safety
type Tool = {
name: string;
description: string;
inputSchema: {
type: "object";
properties: Record<
string,
{ type: string; description: string; enum?: string[] }
>;
required?: string[];
};
};
// Tool descriptions with available indexes (from shared module)
const searchDescription = withIndexList(SEARCH_DESCRIPTION, indexListStr);
const listFilesDescription = withIndexList(LIST_FILES_DESCRIPTION, indexListStr);
const readFileDescription = withIndexList(READ_FILE_DESCRIPTION, indexListStr);
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
const tools: Tool[] = [
{
name: "search",
description: searchDescription,
inputSchema: {
type: "object",
properties: {
index_name: {
type: "string",
description: "Name of the index to search.",
enum: indexNames,
},
query: {
type: "string",
description: "Natural language description of what you're looking for.",
},
maxChars: {
type: "number",
description: "Maximum characters in response (optional).",
},
},
required: ["index_name", "query"],
},
},
];
// Only advertise file tools if not in search-only mode
if (!searchOnly) {
tools.push(
{
name: "list_files",
description: listFilesDescription,
inputSchema: {
type: "object",
properties: {
index_name: {
type: "string",
description: "Name of the index.",
enum: indexNames,
},
directory: {
type: "string",
description: "Directory to list (default: root).",
},
pattern: {
type: "string",
description: "Glob pattern to filter results (e.g., '*.ts', 'src/*.json').",
},
depth: {
type: "number",
description: "Maximum depth to recurse (default: 2). Use 1 for immediate children only.",
},
showHidden: {
type: "boolean",
description: "Include hidden files starting with '.' (default: false).",
},
},
required: ["index_name"],
},
},
{
name: "read_file",
description: readFileDescription,
inputSchema: {
type: "object",
properties: {
index_name: {
type: "string",
description: "Name of the index.",
enum: indexNames,
},
path: {
type: "string",
description: "Path to the file to read, relative to the source root.",
},
startLine: {
type: "number",
description: "First line to read (1-based, inclusive). Default: 1.",
},
endLine: {
type: "number",
description: "Last line to read (1-based, inclusive). Use -1 for end of file. Default: -1.",
},
searchPattern: {
type: "string",
description: "Regex pattern to search for. Only matching lines and context will be shown.",
},
contextLinesBefore: {
type: "number",
description: "Lines of context before each regex match (default: 5).",
},
contextLinesAfter: {
type: "number",
description: "Lines of context after each regex match (default: 5).",
},
includeLineNumbers: {
type: "boolean",
description: "Include line numbers in output (default: true).",
},
},
required: ["index_name", "path"],
},
}
);
}
return { tools };
});
// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
const indexName = args?.index_name as string;
const client = await runner.getClient(indexName);
switch (name) {
case "search": {
const result = await client.search(args?.query as string, {
maxOutputLength: args?.maxChars as number | undefined,
});
return {
content: [
{ type: "text", text: result.results || "No results found." },
],
};
}
case "list_files": {
if (searchOnly) {
return {
content: [{ type: "text", text: "File operations disabled (search-only mode)" }],
isError: true,
};
}
const listOpts = {
directory: args?.directory as string | undefined,
pattern: args?.pattern as string | undefined,
depth: args?.depth as number | undefined,
showHidden: args?.showHidden as boolean | undefined,
};
const result = await client.listFiles(listOpts);
const { formatListOutput } = await import("../tools/list-files.js");
const text = formatListOutput(result, listOpts);
return {
content: [{ type: "text", text }],
};
}
case "read_file": {
if (searchOnly) {
return {
content: [{ type: "text", text: "File operations disabled (search-only mode)" }],
isError: true,
};
}
const result = await client.readFile(args?.path as string, {
startLine: args?.startLine as number | undefined,
endLine: args?.endLine as number | undefined,
searchPattern: args?.searchPattern as string | undefined,
contextLinesBefore: args?.contextLinesBefore as number | undefined,
contextLinesAfter: args?.contextLinesAfter as number | undefined,
includeLineNumbers: args?.includeLineNumbers as boolean | undefined,
});
if (result.error) {
let errorText = `Error: ${result.error}`;
if (result.suggestions && result.suggestions.length > 0) {
errorText += `\n\nDid you mean one of these?\n${result.suggestions.map((s) => ` - ${s}`).join("\n")}`;
}
return {
content: [{ type: "text", text: errorText }],
isError: true,
};
}
return {
content: [{ type: "text", text: result.contents ?? "" }],
};
}
default:
return {
content: [{ type: "text", text: `Unknown tool: ${name}` }],
isError: true,
};
}
} catch (error) {
return {
content: [{ type: "text", text: `Error: ${error}` }],
isError: true,
};
}
});
return server;
}
/**
* Run an MCP server with stdio transport.
*
* This is the main entry point for running the MCP server.
* It creates the server and connects it to stdin/stdout for
* communication with the MCP client.
*
* This function does not return until the server is stopped.
*
* @param config - Server configuration
*
* @example
* ```typescript
* // Serve all indexes in the store
* await runMCPServer({
* store: new FilesystemStore(),
* });
*
* // Serve specific indexes only
* await runMCPServer({
* store: new FilesystemStore(),
* indexNames: ["react", "docs"],
* });
* ```
*/
export async function runMCPServer(config: MCPServerConfig): Promise<void> {
const server = await createMCPServer(config);
const transport = new StdioServerTransport();
await server.connect(transport);
}