-
Notifications
You must be signed in to change notification settings - Fork 60k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support MCP( WIP) #5974
Open
Leizhenpeng
wants to merge
14
commits into
main
Choose a base branch
from
feat-mcp
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Support MCP( WIP) #5974
Changes from 7 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e1c7c54
chore: change md
Leizhenpeng c3108ad
feat: simple MCP example
Kadxy 664879b
feat: Create all MCP Servers at startup
Kadxy e1ba8f1
feat: Send MCP response as a user
Kadxy fe67f79
feat: MCP message type
Kadxy 77be190
feat: carry mcp primitives content as a system prompt
Kadxy f2a2b40
feat: carry mcp primitives content as a system prompt
Kadxy 0c14ce6
fix: MCP execution content matching failed.
Kadxy 7d51bfd
feat: MCP market
Kadxy b410ec3
feat: auto scroll to bottom when MCP response
Kadxy 125a71f
fix: unnecessary initialization
Kadxy e95c94d
fix: inaccurate content
Kadxy a3af563
feat: Reset mcp_config.json to empty
Kadxy ce13cf6
feat: ignore mcp_config.json
Kadxy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
public/serviceWorker.js | ||
public/serviceWorker.js | ||
app/mcp/mcp_config.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
"use server"; | ||
import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | ||
import { | ||
createClient, | ||
executeRequest, | ||
listPrimitives, | ||
Primitive, | ||
} from "./client"; | ||
import { MCPClientLogger } from "./logger"; | ||
import conf from "./mcp_config.json"; | ||
import { McpRequestMessage } from "./types"; | ||
|
||
const logger = new MCPClientLogger("MCP Actions"); | ||
|
||
// Use Map to store all clients | ||
const clientsMap = new Map< | ||
string, | ||
{ client: Client; primitives: Primitive[] } | ||
>(); | ||
|
||
// Whether initialized | ||
let initialized = false; | ||
|
||
// Store failed clients | ||
let errorClients: string[] = []; | ||
|
||
// Initialize all configured clients | ||
export async function initializeMcpClients() { | ||
// If already initialized, return | ||
if (initialized) { | ||
return; | ||
} | ||
|
||
logger.info("Starting to initialize MCP clients..."); | ||
|
||
// Initialize all clients, key is clientId, value is client config | ||
for (const [clientId, config] of Object.entries(conf.mcpServers)) { | ||
try { | ||
logger.info(`Initializing MCP client: ${clientId}`); | ||
const client = await createClient(config, clientId); | ||
const primitives = await listPrimitives(client); | ||
clientsMap.set(clientId, { client, primitives }); | ||
logger.success( | ||
`Client [${clientId}] initialized, ${primitives.length} primitives supported`, | ||
); | ||
} catch (error) { | ||
errorClients.push(clientId); | ||
logger.error(`Failed to initialize client ${clientId}: ${error}`); | ||
} | ||
} | ||
|
||
initialized = true; | ||
|
||
if (errorClients.length > 0) { | ||
logger.warn(`Failed to initialize clients: ${errorClients.join(", ")}`); | ||
} else { | ||
logger.success("All MCP clients initialized"); | ||
} | ||
|
||
const availableClients = await getAvailableClients(); | ||
|
||
logger.info(`Available clients: ${availableClients.join(",")}`); | ||
} | ||
|
||
// Execute MCP request | ||
export async function executeMcpAction( | ||
clientId: string, | ||
request: McpRequestMessage, | ||
) { | ||
try { | ||
// Find the corresponding client | ||
const client = clientsMap.get(clientId)?.client; | ||
if (!client) { | ||
logger.error(`Client ${clientId} not found`); | ||
return; | ||
} | ||
|
||
logger.info(`Executing MCP request for ${clientId}`); | ||
|
||
// Execute request and return result | ||
return await executeRequest(client, request); | ||
} catch (error) { | ||
logger.error(`MCP execution error: ${error}`); | ||
throw error; | ||
} | ||
} | ||
|
||
// Get all available client IDs | ||
export async function getAvailableClients() { | ||
return Array.from(clientsMap.keys()).filter( | ||
(clientId) => !errorClients.includes(clientId), | ||
); | ||
} | ||
|
||
// Get all primitives from all clients | ||
export async function getAllPrimitives(): Promise< | ||
{ | ||
clientId: string; | ||
primitives: Primitive[]; | ||
}[] | ||
> { | ||
return Array.from(clientsMap.entries()).map(([clientId, { primitives }]) => ({ | ||
clientId, | ||
primitives, | ||
})); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | ||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; | ||
import { MCPClientLogger } from "./logger"; | ||
import { McpRequestMessage } from "./types"; | ||
import { z } from "zod"; | ||
|
||
export interface ServerConfig { | ||
command: string; | ||
args?: string[]; | ||
env?: Record<string, string>; | ||
} | ||
|
||
const logger = new MCPClientLogger(); | ||
|
||
export async function createClient( | ||
serverConfig: ServerConfig, | ||
name: string, | ||
): Promise<Client> { | ||
logger.info(`Creating client for server ${name}`); | ||
|
||
const transport = new StdioClientTransport({ | ||
command: serverConfig.command, | ||
args: serverConfig.args, | ||
env: serverConfig.env, | ||
}); | ||
const client = new Client( | ||
{ | ||
name: `nextchat-mcp-client-${name}`, | ||
version: "1.0.0", | ||
}, | ||
{ | ||
capabilities: { | ||
// roots: { | ||
// listChanged: true, | ||
// }, | ||
}, | ||
}, | ||
); | ||
await client.connect(transport); | ||
return client; | ||
} | ||
|
||
export interface Primitive { | ||
type: "resource" | "tool" | "prompt"; | ||
value: any; | ||
} | ||
|
||
/** List all resources, tools, and prompts */ | ||
export async function listPrimitives(client: Client): Promise<Primitive[]> { | ||
const capabilities = client.getServerCapabilities(); | ||
const primitives: Primitive[] = []; | ||
const promises = []; | ||
if (capabilities?.resources) { | ||
promises.push( | ||
client.listResources().then(({ resources }) => { | ||
resources.forEach((item) => | ||
primitives.push({ type: "resource", value: item }), | ||
); | ||
}), | ||
); | ||
} | ||
if (capabilities?.tools) { | ||
promises.push( | ||
client.listTools().then(({ tools }) => { | ||
tools.forEach((item) => primitives.push({ type: "tool", value: item })); | ||
}), | ||
); | ||
} | ||
if (capabilities?.prompts) { | ||
promises.push( | ||
client.listPrompts().then(({ prompts }) => { | ||
prompts.forEach((item) => | ||
primitives.push({ type: "prompt", value: item }), | ||
); | ||
}), | ||
); | ||
} | ||
await Promise.all(promises); | ||
return primitives; | ||
} | ||
|
||
/** Execute a request */ | ||
export async function executeRequest( | ||
client: Client, | ||
request: McpRequestMessage, | ||
) { | ||
return client.request(request, z.any()); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { createClient, listPrimitives } from "@/app/mcp/client"; | ||
import { MCPClientLogger } from "@/app/mcp/logger"; | ||
import conf from "./mcp_config.json"; | ||
|
||
const logger = new MCPClientLogger("MCP Server Example", true); | ||
|
||
const TEST_SERVER = "everything"; | ||
|
||
async function main() { | ||
logger.info(`All MCP servers: ${Object.keys(conf.mcpServers).join(", ")}`); | ||
|
||
logger.info(`Connecting to server ${TEST_SERVER}...`); | ||
|
||
const client = await createClient(conf.mcpServers[TEST_SERVER], TEST_SERVER); | ||
const primitives = await listPrimitives(client); | ||
|
||
logger.success(`Connected to server ${TEST_SERVER}`); | ||
|
||
logger.info( | ||
`${TEST_SERVER} supported primitives:\n${JSON.stringify( | ||
primitives.filter((i) => i.type === "tool"), | ||
null, | ||
2, | ||
)}`, | ||
); | ||
} | ||
|
||
main().catch((error) => { | ||
logger.error(error); | ||
process.exit(1); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Replace 'any' type with a more specific type.
Using 'any' type reduces type safety. Consider defining specific types for resource, tool, and prompt values.