feat: Create all MCP Servers at startup

This commit is contained in:
Kadxy
2024-12-28 21:06:26 +08:00
parent c3108ad333
commit 664879b9df
11 changed files with 134 additions and 165 deletions

View File

@@ -1,35 +1,16 @@
import { createClient, listPrimitives } from "@/app/mcp/client";
import { MCPClientLogger } from "@/app/mcp/logger";
import { z } from "zod";
import { MCP_CONF } from "@/app/mcp/mcp_config";
import conf from "./mcp_config.json";
const logger = new MCPClientLogger("MCP FS Example", true);
const ListAllowedDirectoriesResultSchema = z.object({
content: z.array(
z.object({
type: z.string(),
text: z.string(),
}),
),
});
const ReadFileResultSchema = z.object({
content: z.array(
z.object({
type: z.string(),
text: z.string(),
}),
),
});
const logger = new MCPClientLogger("MCP Server Example", true);
async function main() {
logger.info("Connecting to server...");
const client = await createClient(MCP_CONF.filesystem, "fs");
const client = await createClient(conf.mcpServers.everything, "everything");
const primitives = await listPrimitives(client);
logger.success(`Connected to server fs`);
logger.success(`Connected to server everything`);
logger.info(
`server capabilities: ${Object.keys(
@@ -37,53 +18,11 @@ async function main() {
).join(", ")}`,
);
logger.debug("Server supports the following primitives:");
logger.info("Server supports the following primitives:");
primitives.forEach((primitive) => {
logger.debug("\n" + JSON.stringify(primitive, null, 2));
logger.info("\n" + JSON.stringify(primitive, null, 2));
});
const listAllowedDirectories = async () => {
const result = await client.request(
{
method: "tools/call",
params: {
name: "list_allowed_directories",
arguments: {},
},
},
ListAllowedDirectoriesResultSchema,
);
logger.success(`Allowed directories: ${result.content[0].text}`);
return result;
};
const readFile = async (path: string) => {
const result = await client.request(
{
method: "tools/call",
params: {
name: "read_file",
arguments: {
path: path,
},
},
},
ReadFileResultSchema,
);
logger.success(`File contents for ${path}:\n${result.content[0].text}`);
return result;
};
try {
logger.info("Example 1: List allowed directories\n");
await listAllowedDirectories();
logger.info("\nExample 2: Read a file\n");
await readFile("/users/kadxy/desktop/test.txt");
} catch (error) {
logger.error(`Error executing examples: ${error}`);
}
}
main().catch((error) => {