-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathindex.ts
More file actions
1241 lines (1088 loc) · 35.1 KB
/
index.ts
File metadata and controls
1241 lines (1088 loc) · 35.1 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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { fileURLToPath } from "url";
import { dirname } from "path";
import {
CallToolRequest,
CallToolRequestSchema,
ListToolsRequestSchema,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
import { spawn, ChildProcess } from "child_process";
import * as fs from "fs/promises";
import * as path from "path";
import { v4 as uuidv4 } from "uuid";
import * as os from "os";
// Type definitions for tool arguments
interface CreateServerArgs {
code: string;
language: "typescript" | "javascript" | "python";
}
interface CreateServerFromTemplateArgs {
language: "typescript" | "python";
code?: string;
dependencies?: Record<string, string>; // 例: { "axios": "^1.0.0" }
}
interface ExecuteToolArgs {
serverId: string;
toolName: string;
args: Record<string, any>;
}
interface GetServerToolsArgs {
serverId: string;
}
interface UpdateServerArgs {
serverId: string;
code: string;
}
interface DeleteServerArgs {
serverId: string;
}
interface ConnectedServer {
process: ChildProcess;
client: Client;
transport: StdioClientTransport;
language: string;
filePath: string;
}
// Get current file path and directory in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// コマンドの絶対パスを取得する関数を追加
async function getCommandPath(command: string): Promise<string> {
try {
// whichコマンドの代わりにJavaScriptで絶対パスを探す
const possiblePaths = [
"/usr/local/bin",
"/usr/bin",
"/bin",
"/usr/local/sbin",
"/usr/sbin",
"/sbin",
];
for (const dir of possiblePaths) {
const fullPath = path.join(dir, command);
try {
await fs.access(fullPath, fs.constants.X_OK);
console.error(`Found command ${command} at ${fullPath}`);
return fullPath;
} catch {
// このパスにコマンドが存在しない場合は次を試す
}
}
// コマンドが見つからない場合は元のコマンド名を返す
console.error(
`Command ${command} not found in standard paths, returning as is`
);
return command;
} catch (error) {
console.error(`Error resolving path for ${command}:`, error);
return command;
}
}
// Server manager class
class ServerManager {
private servers: Map<string, ConnectedServer> = new Map();
private templatesDir: string = path.join(__dirname, "templates");
private serversDir: string = path.join(os.tmpdir(), "mcp-create-servers");
constructor() {
// Ensure servers directory exists
this.initDirectories();
}
private async initDirectories() {
try {
await fs.mkdir(this.serversDir, { recursive: true });
// 権限を明示的に設定(Docker内でも動作するように)
await fs.chmod(this.serversDir, 0o777);
console.error(`Created servers directory: ${this.serversDir}`);
} catch (error) {
console.error(`Error creating servers directory: ${error}`);
}
}
// Create a new server from code
async createServer(
code: string,
language: string,
dependencies?: Record<string, string>
): Promise<string> {
const serverId = uuidv4();
const serverDir = path.join(this.serversDir, serverId);
try {
// Create server directory
await fs.mkdir(serverDir, { recursive: true });
await fs.chmod(serverDir, 0o777); // 権限を追加
// 依存関係がある場合はインストール(シンボリックリンクは作成しない)
if (dependencies && Object.keys(dependencies).length > 0) {
await this.installDependencies(serverDir, dependencies, language);
} else {
// 依存関係がない場合のみシンボリックリンクを作成
try {
await fs.symlink(
"/app/node_modules",
path.join(serverDir, "node_modules")
);
console.error(`Created symlink to node_modules in ${serverDir}`);
} catch (error) {
console.error(`Error creating symlink: ${error}`);
// エラーがあっても続行する
}
}
// Write server code to file
let filePath: string;
let command: string;
let args: string[] = [];
// 共通の環境変数設定
const appNodeModules = path.resolve("/app/node_modules");
const commonEnv = {
...process.env,
PATH: process.env.PATH || "/usr/local/bin:/usr/bin:/bin",
NODE_PATH: appNodeModules,
};
console.error(`Current PATH: ${process.env.PATH}`);
console.error(`Current NODE_PATH: ${process.env.NODE_PATH}`);
switch (language) {
case "typescript":
filePath = path.join(serverDir, "index.ts");
const jsFilePath = path.join(serverDir, "index.js");
const tsConfigPath = path.join(__dirname, "tsconfig.json");
await fs.writeFile(filePath, code);
// 絶対パスを取得して出力
command = await getCommandPath("npx");
console.error(`Using command path for npx: ${command}`);
// TypeScriptをコンパイルする方法に変更
await new Promise<void>((resolve, reject) => {
const tscCommand = "npx";
const tscArgs = [
"tsc",
"--allowJs",
filePath,
"--outDir",
serverDir,
"--target",
"ES2020",
"--module",
"NodeNext",
"--moduleResolution",
"NodeNext",
"--esModuleInterop",
"--skipLibCheck",
"--resolveJsonModule",
];
console.error(
`Compiling TypeScript: ${tscCommand} ${tscArgs.join(" ")}`
);
const compileProcess = spawn(tscCommand, tscArgs, {
stdio: ["ignore", "pipe", "pipe"],
shell: true,
env: commonEnv,
cwd: "/app", // アプリケーションのルートディレクトリを指定
});
compileProcess.stdout.on("data", (data) => {
console.error(`TSC stdout: ${data}`);
});
compileProcess.stderr.on("data", (data) => {
console.error(`TSC stderr: ${data}`);
});
compileProcess.on("exit", (code) => {
if (code === 0) {
console.error(`TypeScript compilation successful`);
resolve();
} else {
console.error(
`TypeScript compilation failed with code ${code}`
);
reject(
new Error(`TypeScript compilation failed with code ${code}`)
);
}
});
});
// コンパイルされたJavaScriptを実行
command = await getCommandPath("node");
args = [jsFilePath];
break;
case "javascript":
filePath = path.join(serverDir, "index.js");
await fs.writeFile(filePath, code);
command = await getCommandPath("node");
args = [filePath];
break;
case "python":
filePath = path.join(serverDir, "server.py");
await fs.writeFile(filePath, code);
command = await getCommandPath("python");
args = [filePath];
break;
default:
throw new Error(`Unsupported language: ${language}`);
}
console.error(`Spawning process: ${command} ${args.join(" ")}`);
// サーバープロセスを起動(パイプに変更)
const childProcess = spawn(command, args, {
stdio: ["pipe", "pipe", "pipe"], // inheritではなくpipeを使用
shell: true,
env: commonEnv,
cwd: process.cwd(),
});
// 標準エラー出力のログ取得
childProcess.stderr.on("data", (data) => {
console.error(`Child process stderr: ${data}`);
});
// 標準出力のログ取得
childProcess.stdout.on("data", (data) => {
console.error(`Child process stdout: ${data}`);
});
// Create MCP client to communicate with the server
const transport = new StdioClientTransport({
command,
args,
env: commonEnv, // 同じ環境変数を使用
});
const client = new Client(
{
name: "mcp-create-client",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
try {
await client.connect(transport);
console.error(`Connected to server ${serverId}`);
} catch (error) {
console.error(`Error connecting to server ${serverId}:`, error);
childProcess.kill();
throw error;
}
// Store server info
this.servers.set(serverId, {
process: childProcess,
client,
transport,
language,
filePath,
});
// Handle process exit
childProcess.on("exit", (code) => {
console.error(`Server ${serverId} exited with code ${code}`);
this.servers.delete(serverId);
});
return serverId;
} catch (error) {
// Clean up on error
console.error(`Error creating server:`, error);
try {
await fs.rm(serverDir, { recursive: true, force: true });
} catch (cleanupError) {
console.error(`Error cleaning up server directory: ${cleanupError}`);
}
throw error;
}
}
// Create a server from template
// async createServerFromTemplate(
// language: string
// ): Promise<{ serverId: string; message: string }> {
// // Template code for different languages
// let templateCode: string;
// switch (language) {
// case "typescript":
// templateCode = `
// import { Server } from "@modelcontextprotocol/sdk/server/index.js";
// import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
// import {
// CallToolRequestSchema,
// ListToolsRequestSchema
// } from "@modelcontextprotocol/sdk/types.js";
// const server = new Server({
// name: "dynamic-test-server",
// version: "1.0.0"
// }, {
// capabilities: {
// tools: {}
// }
// });
// // Server implementation - 正しいスキーマ型を使用
// server.setRequestHandler(ListToolsRequestSchema, async () => {
// return {
// tools: [{
// name: "echo",
// description: "Echo back a message",
// inputSchema: {
// type: "object",
// properties: {
// message: { type: "string" }
// },
// required: ["message"]
// }
// }]
// };
// });
// server.setRequestHandler(CallToolRequestSchema, async (request) => {
// if (request.params.name === "echo") {
// return {
// content: [
// {
// type: "text",
// text: \`Echo: \${request.params.arguments.message}\`
// }
// ]
// };
// }
// throw new Error("Tool not found");
// });
// // Server startup
// const transport = new StdioServerTransport();
// server.connect(transport);
// `;
// break;
// case "python":
// templateCode = `
// import asyncio
// from mcp.server import Server
// from mcp.server.stdio import stdio_server
// app = Server("dynamic-test-server")
// @app.list_tools()
// async def list_tools():
// return [
// {
// "name": "echo",
// "description": "Echo back a message",
// "inputSchema": {
// "type": "object",
// "properties": {
// "message": {"type": "string"}
// },
// "required": ["message"]
// }
// }
// ]
// @app.call_tool()
// async def call_tool(name, arguments):
// if name == "echo":
// return [{"type": "text", "text": f"Echo: {arguments.get('message')}"}]
// raise ValueError(f"Tool not found: {name}")
// async def main():
// async with stdio_server() as streams:
// await app.run(
// streams[0],
// streams[1],
// app.create_initialization_options()
// )
// if __name__ == "__main__":
// asyncio.run(main())
// `;
// break;
// default:
// throw new Error(`Unsupported template language: ${language}`);
// }
// const serverId = await this.createServer(templateCode, language);
// return {
// serverId,
// message: `Created server from ${language} template`,
// };
// }
// 以下は他のメソッドも同様に修正することになりますが、
// 主要な変更点は上記の通りです
// 依存関係をインストールするメソッド
async installDependencies(
serverDir: string,
dependencies: Record<string, string>,
language: string
): Promise<void> {
console.error(`Installing dependencies for ${language} in ${serverDir}`);
switch (language) {
case "typescript":
case "javascript":
await this.installNodeDependencies(serverDir, dependencies);
break;
case "python":
await this.installPythonDependencies(serverDir, dependencies);
break;
default:
throw new Error(`Unsupported language for dependencies: ${language}`);
}
}
// Node.js (TypeScript/JavaScript) 用の依存関係インストール
private async installNodeDependencies(
serverDir: string,
dependencies: Record<string, string>
): Promise<void> {
try {
// 既存のpackage.jsonを読み込む(存在する場合)
let packageJson: any = {
name: "mcp-dynamic-server",
version: "1.0.0",
type: "module",
dependencies: {}
};
// アプリケーションのpackage.jsonを読み込む
try {
const appPackageJsonPath = path.join("/app", "package.json");
const appPackageJsonContent = await fs.readFile(appPackageJsonPath, 'utf-8');
const appPackageJson = JSON.parse(appPackageJsonContent);
// 必要な依存関係をマージ
if (appPackageJson.dependencies) {
// 特に@modelcontextprotocol関連の依存関係をコピー
Object.entries(appPackageJson.dependencies).forEach(([pkg, ver]) => {
if (pkg.startsWith('@modelcontextprotocol') || pkg === 'mcp') {
packageJson.dependencies[pkg] = ver;
}
});
}
console.error(`Merged dependencies from app package.json`);
} catch (error) {
console.error(`Error reading app package.json:`, error);
// エラーがあっても続行
}
// ユーザー指定の依存関係をマージ
Object.entries(dependencies).forEach(([pkg, ver]) => {
packageJson.dependencies[pkg] = ver;
});
// package.jsonを書き込む
await fs.writeFile(
path.join(serverDir, "package.json"),
JSON.stringify(packageJson, null, 2)
);
// npm install の実行
const npmCommand = await getCommandPath("npm");
await new Promise<void>((resolve, reject) => {
const installProcess = spawn(
npmCommand,
["install"],
{
stdio: ["ignore", "pipe", "pipe"],
shell: true,
env: { ...process.env },
cwd: serverDir
}
);
installProcess.stdout.on("data", (data) => {
console.error(`NPM stdout: ${data}`);
});
installProcess.stderr.on("data", (data) => {
console.error(`NPM stderr: ${data}`);
});
installProcess.on("exit", (code) => {
if (code === 0) {
console.error(`NPM install successful`);
resolve();
} else {
console.error(`NPM install failed with code ${code}`);
reject(new Error(`NPM install failed with code ${code}`));
}
});
});
} catch (error) {
console.error(`Error installing Node.js dependencies:`, error);
throw error;
}
}
// Python 用の依存関係インストール
private async installPythonDependencies(
serverDir: string,
dependencies: Record<string, string>
): Promise<void> {
try {
// requirements.txt の作成
const requirementsContent = Object.entries(dependencies)
.map(([pkg, ver]) => `${pkg}${ver}`)
.join("\n");
await fs.writeFile(
path.join(serverDir, "requirements.txt"),
requirementsContent
);
// pip install の実行
const pipCommand = await getCommandPath("pip");
await new Promise<void>((resolve, reject) => {
const installProcess = spawn(
pipCommand,
["install", "-r", "requirements.txt"],
{
stdio: ["ignore", "pipe", "pipe"],
shell: true,
env: { ...process.env },
cwd: serverDir
}
);
installProcess.stdout.on("data", (data) => {
console.error(`PIP stdout: ${data}`);
});
installProcess.stderr.on("data", (data) => {
console.error(`PIP stderr: ${data}`);
});
installProcess.on("exit", (code) => {
if (code === 0) {
console.error(`PIP install successful`);
resolve();
} else {
console.error(`PIP install failed with code ${code}`);
reject(new Error(`PIP install failed with code ${code}`));
}
});
});
} catch (error) {
console.error(`Error installing Python dependencies:`, error);
throw error;
}
}
// Execute a tool on a server
async executeToolOnServer(
serverId: string,
toolName: string,
args: Record<string, any>
): Promise<any> {
const server = this.servers.get(serverId);
if (!server) {
throw new Error(`Server ${serverId} not found`);
}
try {
// Call the tool on the server using the MCP client
const result = await server.client.callTool({
name: toolName,
arguments: args,
});
return result;
} catch (error) {
console.error(`Error executing tool on server ${serverId}:`, error);
throw error;
}
}
// Get tools from a server
async getServerTools(serverId: string): Promise<any> {
const server = this.servers.get(serverId);
if (!server) {
throw new Error(`Server ${serverId} not found`);
}
try {
// Get tools from the server using the MCP client
const tools = await server.client.listTools();
return tools;
} catch (error) {
console.error(`Error getting tools from server ${serverId}:`, error);
throw error;
}
}
// Update a server
async updateServer(
serverId: string,
code: string
): Promise<{ success: boolean; message: string }> {
const server = this.servers.get(serverId);
if (!server) {
throw new Error(`Server ${serverId} not found`);
}
try {
// Update server code
await fs.writeFile(server.filePath, code);
// Close the client connection
await server.transport.close();
// Kill the server process
server.process.kill();
// Wait for process to exit
await new Promise<void>((resolve) => {
server.process.on("exit", () => {
resolve();
});
});
// Remove the server from the map
this.servers.delete(serverId);
// Create new server with updated code
const newServerId = await this.createServer(code, server.language);
return {
success: true,
message: `Server ${serverId} updated and restarted as ${newServerId}`,
};
} catch (error) {
console.error(`Error updating server ${serverId}:`, error);
throw error;
}
}
// Delete a server
async deleteServer(
serverId: string
): Promise<{ success: boolean; message: string }> {
const server = this.servers.get(serverId);
if (!server) {
throw new Error(`Server ${serverId} not found`);
}
try {
// Close the client connection
await server.transport.close();
// Kill server process
server.process.kill();
// Remove server from map
this.servers.delete(serverId);
// Delete server directory
const serverDir = path.dirname(server.filePath);
await fs.rm(serverDir, { recursive: true, force: true });
return {
success: true,
message: `Server ${serverId} deleted`,
};
} catch (error) {
console.error(`Error deleting server ${serverId}:`, error);
throw error;
}
}
// List all servers
listServers(): string[] {
return Array.from(this.servers.keys());
}
// Close all servers
async closeAll(): Promise<void> {
for (const [serverId, server] of this.servers.entries()) {
try {
await server.transport.close();
server.process.kill();
console.error(`Closed server ${serverId}`);
} catch (error) {
console.error(`Error closing server ${serverId}:`, error);
}
}
this.servers.clear();
}
}
// Tool definitions
// const createServerTool: Tool = {
// name: "create-server",
// description: "Create a new MCP server from code",
// inputSchema: {
// type: "object",
// properties: {
// code: {
// type: "string",
// description: "The server code",
// },
// language: {
// type: "string",
// enum: ["typescript", "javascript", "python"],
// description: "The programming language of the server code",
// },
// },
// required: ["code", "language"],
// },
// };
const createServerFromTemplateTool: Tool = {
name: "create-server-from-template",
description: `Create a new MCP server from a template.
以下のテンプレートコードをベースに、ユーザーの要求に合わせたサーバーを実装してください。
言語に応じて適切なテンプレートを選択し、必要に応じて機能を追加・変更してください。
TypeScriptテンプレート:
\`\`\`typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
const server = new Server({
name: "dynamic-test-server",
version: "1.0.0"
}, {
capabilities: {
tools: {}
}
});
// ここでツールを実装してください
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [{
name: "echo",
description: "Echo back a message",
inputSchema: {
type: "object",
properties: {
message: { type: "string" }
},
required: ["message"]
}
}]
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "echo") {
// TypeScriptの型を適切に扱うため、型アサーションを使用
const message = request.params.arguments.message as string;
// または any を使う: const message: any = request.params.arguments.message;
return {
content: [
{
type: "text",
text: \`Echo: \${message}\`
}
]
};
}
throw new Error("Tool not found");
});
// Server startup
const transport = new StdioServerTransport();
server.connect(transport);
\`\`\`
Pythonテンプレート:
\`\`\`python
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server
app = Server("dynamic-test-server")
@app.list_tools()
async def list_tools():
return [
{
"name": "echo",
"description": "Echo back a message",
"inputSchema": {
"type": "object",
"properties": {
"message": {"type": "string"}
},
"required": ["message"]
}
}
]
@app.call_tool()
async def call_tool(name, arguments):
if name == "echo":
return [{"type": "text", "text": f"Echo: {arguments.get('message')}"}]
raise ValueError(f"Tool not found: {name}")
async def main():
async with stdio_server() as streams:
await app.run(
streams[0],
streams[1],
app.create_initialization_options()
)
if __name__ == "__main__":
asyncio.run(main())
\`\`\`
注意事項:
- TypeScript実装時は、引数の型を適切に扱うために型アサーション(as string)を使用するか、
明示的に型を宣言してください(例:const value: string = request.params.arguments.someValue)。
- 複雑な型を扱う場合は、interface や type を定義して型安全性を確保することをお勧めします。
ユーザーの要求に応じて上記のテンプレートを参考にカスタマイズしてください。その際、基本的な構造を維持しつつ、ツール名や機能を変更できます。`,
inputSchema: {
type: "object",
properties: {
language: {
type: "string",
enum: ["typescript", "python"],
description: "The programming language for the template",
},
code: {
type: "string",
description:
"カスタマイズしたサーバーコード。テンプレートを元に変更したコードを入力してください。省略した場合はデフォルトのテンプレートが使用されます。",
},
dependencies: {
type: "object",
description: "使用するライブラリとそのバージョン(例: { \"axios\": \"^1.0.0\" })",
},
},
required: ["language"],
},
};
const executeToolTool: Tool = {
name: "execute-tool",
description: "Execute a tool on a server",
inputSchema: {
type: "object",
properties: {
serverId: {
type: "string",
description: "The ID of the server",
},
toolName: {
type: "string",
description: "The name of the tool to execute",
},
args: {
type: "object",
description: "The arguments to pass to the tool",
},
},
required: ["serverId", "toolName"],
},
};
const getServerToolsTool: Tool = {
name: "get-server-tools",
description: "Get the tools available on a server",
inputSchema: {
type: "object",
properties: {
serverId: {
type: "string",
description: "The ID of the server",
},
},
required: ["serverId"],
},
};
// const updateServerTool: Tool = {
// name: "update-server",
// description: `Update a server's code.まずupdate前のコードを読み、その内容からupdateの差分を考えてください。
// その差分をもとに、update後のコードを作成してください。`,
// inputSchema: {
// type: "object",
// properties: {
// serverId: {
// type: "string",
// description: "The ID of the server",
// },
// code: {
// type: "string",
// description: `The new server code.
// `,
// },
// },
// required: ["serverId", "code"],
// },
// };
const deleteServerTool: Tool = {
name: "delete-server",
description: "Delete a server",
inputSchema: {
type: "object",
properties: {
serverId: {
type: "string",
description: "The ID of the server",
},
},
required: ["serverId"],
},
};
const listServersTool: Tool = {
name: "list-servers",
description: "List all running servers",
inputSchema: {
type: "object",
properties: {},
},
};
async function main() {
try {
console.error("Starting MCP Create Server...");
const server = new Server(
{
name: "MCP Create Server",
version: "1.0.0",
},
{