# @genkit-ai/mcp 中文文档

规范地址：https://npmcn.com/package/%40genkit-ai/mcp/

版本：1\.44\.0
npm 元数据更新时间：2026-11-03T20:52:42.878Z
中文译文更新时间：2026-11-16T03:45:54.481Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40genkit-ai/mcp
原文对照：https://npmcn.com/package/%40genkit-ai/mcp/?lang=original
项目主页：https://github.com/genkit-ai/genkit#readme
源码仓库：https://github.com/genkit-ai/genkit

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：567 kB，89 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：genkit ^1\.44\.0，@modelcontextprotocol/sdk ^1\.29\.0
- 首次发布：2025-07-10T23:19:42.830Z
- 最新版本发布：2026-11-03T20:52:42.655Z
- 近 30 天下载量：19557（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：69（近 12 个月 40 个）

## 中文简介

一个提供Genkit和模型背景协议(MCP)之间的互操作性的Genkit插件. 支持客户端和服务器使用大小写.

## 安装

```sh
npm install @genkit-ai/mcp
```

也可以使用：`pnpm add @genkit-ai/mcp`、`yarn add @genkit-ai/mcp`、`bun add @genkit-ai/mcp`

## README

# Genkit MCP 变相器

见 [Genkit MCP 文档](https://genkit.dev/docs/model-context-protocol/)。 。 。 .

> **用编码代理? 先安装基因组JS技能.**
> 
> ```bash
> npx skills add genkit-ai/skills --skill developing-genkit-js
> ```
> 
> 它教你的代理人 现任Genkit JS APIs 和普通的gitchas. 其他语言的来源、人工安装和技能: [技能/技能](https://github.com/genkit-ai/skills)。 。 。 .

此插件可提供 Genkit 和 Genkit 之间的整合 [示范背景协议](https://modelcontextprotocol.io/) (中文(简体) ). MCP是一个开放标准,允许开发者建立"服务器",为客户端提供工具,资源并提供提示. Genkit MCP允许Genkit开发者:

-   使用 MCP 工具、 提示和资源作为客户端 `createMcpHost` 或者说 `createMcpClient`。 。 。 .
-   使用 Genkit 作为 MCP 服务器提供 Genkit 工具和提示 `createMcpServer`。 。 。 .

## 安装

要启动, 您需要 Genkit 和 MCP 插件:

```bash
npm i genkit @genkit-ai/mcp
```

## MCP 主机

要连接一个或多个 MCP 服务器,请使用 `createMcpHost` 函数。 此函数返回 a `GenkitMcpHost` 实例管理已配置的 MCP 服务器的连接.

```ts
import { googleAI } from '@genkit-ai/google-genai';
import { createMcpHost } from '@genkit-ai/mcp';
import { genkit } from 'genkit';

const mcpHost = createMcpHost({
  name: 'myMcpClients', // A name for the host plugin itself
  mcpServers: {
    // Each key (e.g., 'fs', 'git') becomes a namespace for the server's tools.
    fs: {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-filesystem', process.cwd()],
    },
    memory: {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-memory'],
    },
  },
});

const ai = genkit({
  plugins: [googleAI()],
});

(async () => {
  // Provide MCP tools to the model of your choice.
  const { text } = await ai.generate({
    model: googleAI.model('gemini-flash-latest'),
    prompt: `Analyze all files in ${process.cwd()}.`,
    tools: await mcpHost.getActiveTools(ai),
    resources: await mcpHost.getActiveResources(ai),
  });

  console.log(text);

  await mcpHost.close();
})();
```

这个 `createMcpHost` 函数初始化 a `GenkitMcpHost` 例如,它处理生命周期,并与定义的MCP服务器进行通信.

### `createMcpHost()` 选项

-   **`name`**: (可选,字符串) MCP 主机插件本身的名称. 默认为“ genkitx- mcp ” .
    
-   **`version`**: (可选,字符串) MCP主机插件的版本. 默认为"1.0".
    
-   **`rawToolResponses`**: (可选,布尔) 何时 `true`,工具响应以原始的MCP格式返回;否则,它们会被处理成Genkit兼容性. 默认为 `false`。 。 。 .
    
-   **`mcpServers`**: (需要,对象) 每个密钥都是MCP服务器客户端名称(namespace)的对象,其值是该服务器的配置.
    
    每个服务器配置对象可以包括:
    
    -   **`disabled`**: (可选,布尔)如果 `true`,此服务器连接将不会尝试 。 默认为 `false`。 。 。 .
    -   下列服务器连接配置之一:
        -   使用 stdio MCP 传输启动本地服务器进程的参数.
            -   **`command`**: (需要,字符串) 启动 MCP 服务器的 shell 命令路径( 例如 ), `npx`, (中文(简体) ), `python`) (中文(简体) ).
            -   **`args`**: (可选的,字符串\[\]) 要传递到命令的字符串参数组 .
            -   **`env`**: (可选, 记录 < string, string > ) 环境变量的关键值对象.
        -   **`url`**: (字符串)一个远程服务器的URL可以连接到使用可流式HTTP MCP传输.
        -   **`transport`**:用于连接服务器的现有MCP传输对象.

## MCP 客户端( 单一服务器)

对于只需要连接到单一的 MCP 服务器,或者更愿意单独管理客户端实例的情景,您可以使用 `createMcpClient`。 。 。 .

```ts
import { googleAI } from '@genkit-ai/google-genai';
import { createMcpClient } from '@genkit-ai/mcp';
import { genkit } from 'genkit';

const myFsClient = createMcpClient({
  name: 'myFileSystemClient', // A unique name for this client instance
  mcpServer: {
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-filesystem', process.cwd()],
  },
  // rawToolResponses: true, // Optional: get raw MCP responses
});

// In your Genkit configuration:
const ai = genkit({
  plugins: [googleAI()],
});

(async () => {
  await myFsClient.ready();

  // Retrieve tools from this specific client
  const fsTools = await myFsClient.getActiveTools(ai);

  const { text } = await ai.generate({
    model: googleAI.model('gemini-flash-latest'), // Replace with your model
    prompt: 'List files in ' + process.cwd(),
    tools: fsTools,
  });
  console.log(text);

  await myFsClient.disable();
})();
```

### `createMcpClient()` 选项

这个 `createMcpClient` 函数需要 `McpClientOptions` 对象 :

-   **`name`**: (需要,字符串) 此客户端实例的独有名称 。 此名称将用作其工具和提示的命名空间 .
-   **`version`**: (可选,字符串) 此客户端实例的版本 。 默认为"1.0".
-   此外,它还支持所有来自 `McpServerConfig` (例如, `disabled`, (中文(简体) ), `rawToolResponses`和运输配置),详见 `createMcpHost` 选项部分.

### 使用 MCP 动作( 工具, 提示)

两者 `GenkitMcpHost` (通过) `getActiveTools()`和 `GenkitMcpClient` (通过) `getActiveTools()`从连接和启用的MCP服务器中发现可用的工具。 这些工具是标准的"玄子" `ToolAction` 实例和可以提供给基因组模型.

MCP 提示可以使用 `McpHost.getPrompt(serverName, promptName)` 或者说 `mcpClient.getPrompt(promptName)`这些返回 `ExecutablePrompt`。 。 。 .

所有 MCP 动作( 工具, 提示, 资源) 都被命名 .

-   对于 `createMcpHost`,命名空间是您为服务器提供的密钥 `mcpServers` 配置(例如, `localFs/read_file`) (中文(简体) ).
-   对于 `createMcpClient`,命名空间是 `name` 您在其选项中提供(例如, `myFileSystemClient/list_resources`) (中文(简体) ).

### 工具响应

MCP 工具返回 a `content` 阵列,而不是像大多数基因组工具那样的结构化响应。 Genkit MCP 插件试图解析并强制返回的内容 :

1.  如果内容为文本并有效JSON,则解析后作为JSON对象返回.
2.  如果内容是文本但无效的JSON,则原始文本被返回.
3.  如果内容包含一个单一的非文本部分(例如图像),则直接返回该部分.
4.  如果内容包含多部分或混合部分(如文本和图像),则完整内容响应阵列被返回.

## MCP 服务器

您也可以使用 MCP 服务器曝光 Genkit 实例中的所有工具和提示 `createMcpServer` 函数.

```ts
import { googleAI } from '@genkit-ai/google-genai';
import { createMcpServer } from '@genkit-ai/mcp';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { genkit, z } from 'genkit/beta';

const ai = genkit({
  plugins: [googleAI()],
});

ai.defineTool(
  {
    name: 'add',
    description: 'add two numbers together',
    inputSchema: z.object({ a: z.number(), b: z.number() }),
    outputSchema: z.number(),
  },
  async ({ a, b }) => {
    return a + b;
  }
);

ai.definePrompt(
  {
    name: 'happy',
    description: 'everybody together now',
    input: {
      schema: z.object({
        action: z.string().default('clap your hands').optional(),
      }),
    },
  },
  `If you're happy and you know it, {{action}}.`
);

ai.defineResource(
  {
    name: 'my resouces',
    uri: 'my://resource',
  },
  async () => {
    return {
      content: [
        {
          text: 'my resource',
        },
      ],
    };
  }
);

ai.defineResource(
  {
    name: 'file',
    template: 'file://{path}',
  },
  async ({ uri }) => {
    return {
      content: [
        {
          text: `file contents for ${uri}`,
        },
      ],
    };
  }
);

// Use createMcpServer
const server = createMcpServer(ai, {
  name: 'example_server',
  version: '0.0.1',
});
// Setup (async) then starts with stdio transport by default
server.setup().then(async () => {
  await server.start();
  const transport = new StdioServerTransport();
  await server!.server?.connect(transport);
});
```

这个 `createMcpServer` 函数返回 a `GenkitMcpServer` 举个例子 这个 `start()` 在此实例上的方法将启动一个 MCP 服务器( 默认使用 stdio 传输) , 该服务器将曝光所有已注册的 Genkit 工具和提示 。 要启动不同的 MCP 传输, 您可以将传输实例传递到 `start()` 方法(例如, `server.start(customMcpTransport)`) (中文(简体) ).

### `createMcpServer()` 选项

-   **`name`**: (需要,字符串) 您想要为 MCP 检查提供服务器的名称 .
-   **`version`**: (可选,字符串) 您的服务器将向客户端发布广告版本 。 默认为"1.0".

### 已知的限制

-   MCP 提示只能取字符串参数,因此对schemas的输入必须是只有字符串属性值的对象.
-   MCP 只提示支持 `user` 财务报告和审定财务报表 `model` 留言. `system` 不支持信件.
-   MCP 提示只支持消息中的单个"类型",所以不能在同一消息中混合媒体和文本.

### 测试您的 MCP 服务器

您可以使用官方检查员测试您的 MCP 服务器 。 例如,如果您的服务器代码编译成 `dist/index.js`,你可以运行:

```
npx @modelcontextprotocol/inspector dist/index.js
```

一旦你开始检查, 你可以列出提示和行动 并手动测试出来.

## 常见问题

### @genkit-ai/mcp 是什么？

一个提供Genkit和模型背景协议\(MCP\)之间的互操作性的Genkit插件\. 支持客户端和服务器使用大小写\.

### 如何安装 @genkit-ai/mcp？

在项目目录运行 npm install @genkit-ai/mcp，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：genkit（^1\.44\.0）、@modelcontextprotocol/sdk（^1\.29\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @genkit-ai/mcp 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @genkit-ai/mcp 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @genkit-ai/mcp 可以商用吗？

@genkit-ai/mcp 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @genkit-ai/mcp 的下载量有多少？

根据 npm 官方下载统计，@genkit-ai/mcp 在 2026/10/16 – 2026/11/14 这 30 天内被下载 19,557 次，日均约 652 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @genkit-ai/mcp 还在维护吗？

最新版本 1\.44\.0 发布于 2026/11/04（12 天前）；至今共发布 69 个版本，其中过去 12 个月发布了 40 个；首次发布于 2025/07/11。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

