本文介绍了主机应用如何使用 MCPMCP列出、连接到和与 odr.exe Windows 上注册的服务器进行交互。 本演练将使用 Windows 示例存储库中的 MCP 示例主机应用 ,github.com/microsoft/mcp-on-windows-samples。
注释
一些信息与预发布产品相关,在商业发行之前可能发生实质性修改。 Microsoft对此处提供的信息不作任何明示或暗示的保证。
先决条件
- Windows 内部版本 26220.7262 或更高版本
-
MCP具有包标识的主机应用。 有关包标识的详细信息,请参阅 Windows 应用中的包标识概述。 将包标识授予使用 MSIX 包格式打包的应用。 有关详细信息,请参阅 什么是 MSIX?。
- 注意 此要求不会在公共预览版中强制执行,但它将在稳定版本中。
克隆示例
将 MCP Windows 主机上的示例 克隆到你的设备并导航到它:
git clone https://github.com/microsoft/mcp-on-windows-samples.git
cd mcp-on-windows-samples/mcp-client-js
设置并生成示例
运行以下命令:
npm install
npm run start
该工具将显示一个命令行 UI,用于与设备上注册的服务器 MCP 进行交互。 以下部分将显示该工具用于实现主机应用的各种功能的 MCP Javascript 代码。
列出可用 MCP 服务器
列出执行命令行调用MCP的可用odr.exe list服务器。 此命令返回 JSON 格式的服务器列表,该列表存储在后续示例中并使用:
const { stdout, stderr } = await execFileAsync('odr.exe', ['list']);
if (stderr) {
console.error('Warning:', stderr);
}
const servers = JSON.parse(stdout);
连接到 MCP 服务器
从上一步返回的 JSON 获取命令和参数,并用其连接到一个可用的 MCP 服务器。 创建一个StdioClientTransport,传入命令和参数。 创建新 Client 对象。 呼叫 连接 以连接到 MCP 服务器。
const command = server.manifest?.server?.mcp_config?.command;
const args = server.manifest?.server?.mcp_config?.args || [];
if (!command) {
throw new Error('Server configuration missing command.');
}
// Create MCP client with stdio transport
// Set stderr to 'ignore' to silence server info logs
const transport = new StdioClientTransport({
command: command,
args: args,
stderr: 'ignore'
});
const client = new Client({
name: 'mcp-client',
version: '1.0.0'
}, {
capabilities: {}
});
// Connect to the server
await client.connect(transport);
列出服务器中的工具
调用 listTools 以列出由 MCP 服务器注册的工具。
// List available tools
const toolsResponse = await client.listTools();
const tools = toolsResponse.tools || [];
调用工具
每个 MCP 工具都有一个名称和一组可选的参数。 示例中的 gatherToolParameters 函数将帮助收集输入参数,然后可以直接调用该工具:
const parameters = await gatherToolParameters(tool); // This function is from the sample code
const result = await client.callTool({
name: tool.name,
arguments: parameters
});
后续步骤
- 了解如何构建和注册一个可被宿主应用发现和使用的MCP服务器。 有关详细信息,请参阅 注册 MCP 服务器。