# @pamcp/bridge

-----

**将本地命令、脚本和API接口无缝转换为强大的MCP（模型上下文协议）工具。**

**@pamcp/bridge** 是一个功能强大的NPM包，它允许您通过简单的JSON配置，将本地的命令行工具、脚本（如Python、Bash）以及HTTP RESTful API端点封装成标准的MCP工具。这些工具可以被任何MCP客户端（如爱码、Cursor、Cline、Windsurf）直接使用，极大地降低了MCP服务的开发成本。

-----

## ✨ 功能特性

@pamcp/bridge 旨在为您提供一个灵活且高效的桥梁，帮助你零门槛轻松的打造专属MCP服务。

  * **🔧 转换Shell命令**
      * 轻松将任何命令行工具或脚本（如Python、Bash脚本、自定义可执行文件）封装成一个标准化的MCP工具。AI编辑器可以像调用内置功能一样调用它们，实现自动化任务执行。
  * **🌐 转换REST API**
      * 将HTTP RESTful API端点无缝转换为MCP工具。这意味着您可以将内部服务、第三方API或其他Web服务集成到您的AI工作流中，实现数据获取和交互。
  * **📝 配置驱动**
      * 无需编写任何代码！所有工具和其行为都通过一个直观的JSON配置文件进行定义。这使得工具的创建、管理和分享变得极其简单。
  * **🚀 多种传输协议支持**
      * 原生支持 `stdio`（标准输入/输出）模式，适用于大多数MCP客户端直接启动和通信。
      * 同时支持 `streamable` HTTP 传输模式，允许作为独立服务器运行，为长期运行的服务或远程客户端提供HTTP连接。
  * **🧩 强大的变量插值**
      * 在命令参数、API端点、请求头或请求体中动态插入变量。通过 `${variable_name}` 语法，您可以根据AI编辑器提供的输入动态调整工具的行为，实现高度灵活和可复用的工具定义。
  * **⚙️ 高度可定制的输入模式**
      * 通过定义 **Input Schema**（遵循JSON Schema标准），您可以精确地指定每个工具所需的参数及其数据类型。这不仅为MCP工具提供了清晰的接口定义，也确保了参数的有效性和正确性。

-----

## 💡 使用指南

@pamcp/bridge 提供了两种主要的使用方式：作为MCP客户端的集成工具，或作为独立的HTTP服务器。

### 核心用法：通过MCP客户端集成

这是使用 **@pamcp/bridge** 的主要方式。在任何MCP客户端（如平安爱码、Cursor、Cline、Windsurf）的MCP配置文件中，您可以直接添加 `mcpServers` 配置。MCP客户端将自动通过 `npx` 下载并运行@pamcp/bridge，无需您手动安装或启动。

  * **通过配置文件方式进行配置**
    将您的工具定义保存为一个JSON文件（例如 `config.json`），然后在MCP配置中引用它。

    ```json
    {
      "mcpServers": {
        "mcp-bridge": {
          "command": "npx",
          "args": [
            "-y",
            "@pamcp/bridge",
            "--config",
            "/absolute/path/to/your/config.json"
          ]
        }
      }
    }
    ```

  * **通过内联JSON方式进行配置**
    对于简单的配置，您可以直接在MCP配置中嵌入JSON字符串。

    ```json
    {
      "mcpServers": {
        "mcp-bridge": {
          "command": "npx",
          "args": [
            "-y",
            "@pamcp/bridge",
            "--configJson",
            "{ \"description\": \"Example bridge server configuration\", \"version\": \"v1\", \"tools\": []}"
          ]
        }
      }
    }
    ```

  * **通过URL方式进行配置**
    适合以共享或根据接口自动生成配置的场景。您只需要提供一个可访问的URL，@pamcp/bridge 将自动从该URL加载配置。

    ```json
    {
      "mcpServers": {
        "mcp-bridge": {
          "command": "npx",
          "args": [
            "-y",
            "@pamcp/bridge",
            "--configUrl",
            "http://api.example.com/pamcp-bridge.json"
          ]
        }
      }
    }
    ```

### 高级用法：作为独立HTTP服务器运行

如果您的客户端需要通过HTTP连接到一个长期运行的服务，而不是动态启动进程，您可以使用 `streamable` 传输模式。这在Web应用、共享服务或需要持续运行后台进程的场景中非常有用。

在终端中运行以下命令，它将在指定端口上启动一个HTTP服务器：

```bash
# 使用 streamable HTTP 传输协议在 3456 端口启动服务，并加载 config.json 配置
npx @pamcp/bridge --transport streamable --port 3456 --config config.json
```

### 命令行参数一览

| 参数         | 别名    | 描述                                                           | 示例                                                               |
| :----------- | :------ | :------------------------------------------------------------- | :----------------------------------------------------------------- |
| `--config`   | `-c`    | 指定一个本地JSON配置文件路径。                                 | `--config ./my_tools.json`                                         |
| `--configJson` | `-j`    | 提供一个内联的JSON字符串作为配置。                             | `--configJson '{"tools":[]}'`                                      |
| `--configUrl`  | `-u`    | 提供一个URL，从远程加载JSON配置文件。                          | `--configUrl https://example.com/remote_config.json`               |
| `--transport`  | `-t`    | 指定传输协议 (`stdio` 或 `streamable`)。默认为 `stdio`。       | `--transport streamable`                                           |
| `--port`     | `-p`    | 当 `transport` 为 `streamable` 时，指定HTTP服务器监听的端口。 | `--port 3456`                                                      |
| `--help`     | `-h`    | 显示帮助信息。                                                 | `--help`                                                           |
| `--version`  | `-v`    | 显示当前版本号。                                               | `--version`                                                        |

-----

## 📝 配置文件格式 (`config.json`)

无论使用哪种方式，您都需要一个 `config.json` 文件（或内联JSON/远程URL加载的内容）来定义您的所有MCP工具。这是 `@pamcp/bridge` 定义所有能力的核心。

以下是一个详细的配置文件示例，解释了 `command` 和 `api` 两种工具类型：

```json
{
    "description": "Example bridge server configuration",
    "version": "v1",
    "tools": [
        {
        "name": "list-files",
        "type": "command",
        "command": "ls",
        "args": ["-la", "${directory}"],
        "description": "List files in a directory",
        "inputSchema": {
            "type": "object",
            "properties": {
            "directory": {
                "type": "string",
                "description": "Directory path to list"
            }
            },
            "required": ["directory"]
        }
        },
        {
        "name": "run-python-script",
        "type": "command",
        "command": "python3",
        "args": ["${script_path}", "${argument}"],
        "cwd": "${working_directory}",
        "description": "Run a Python script with arguments",
        "inputSchema": {
            "type": "object",
            "properties": {
            "script_path": {
                "type": "string",
                "description": "Path to the Python script"
            },
            "argument": {
                "type": "string", 
                "description": "Argument to pass to the script"
            },
            "working_directory": {
                "type": "string",
                "description": "Working directory to run the script in"
            }
            },
            "required": ["script_path"]
        }
        },
        {
        "name": "get-weather",
        "type": "api",
        "endpoint": "https://restapi.amap.com/v3/weather/weatherInfo?key=${api_key}&city=${city}&extensions=all",
        "method": "GET",
        "description": "Get current weather for a city",
        "inputSchema": {
            "type": "object",
            "properties": {
            "city": {
                "type": "string",
                "description": "City name"
            },
            "api_key": {
                "type": "string",
                "description": "AMap API key"
            }
            },
            "required": ["city", "api_key"]
        }
        },
        {
        "name": "create-user",
        "type": "api", 
        "endpoint": "https://jsonplaceholder.typicode.com/users",
        "method": "POST",
        "headers": {
            "Content-Type": "application/json",
            "Authorization": "Bearer ${token}"
        },
        "body": {
            "name": "${name}",
            "email": "${email}"
        },
        "description": "Create a new user",
        "inputSchema": {
            "type": "object",
            "properties": {
            "name": {
                "type": "string",
                "description": "User's full name"
            },
            "email": {
                "type": "string",
                "description": "User's email address"
            },
            "token": {
                "type": "string",
                "description": "Authorization token (optional for this example, but useful)"
            }
            },
            "required": ["name", "email"]
        }
        }
    ]
}
```

### 配置字段说明

  * **`description` (string)**: 对整个bridge服务器配置的描述。
  * **`version` (string)**: 配置的版本号，推荐使用 `v1`。
  * **`tools` (array)**: 包含所有MCP工具定义的核心数组。每个对象代表一个独立的工具。

### 工具定义 (`tools` 数组中的每个对象)

每个工具对象都必须包含以下通用字段：

  * **`name` (string, 必需)**: 工具的唯一名称，AI编辑器将使用此名称来引用和调用工具。推荐使用小驼峰命名法（`camelCase`）。
  * **`type` (string, 必需)**: 工具的类型，目前支持 `command` 或 `api`。
  * **`description` (string, 必需)**: 工具的详细描述，这将帮助AI理解工具的功能和用途。

#### `type: "command"` (命令行工具)

用于将本地命令或脚本封装成MCP工具。

  * **`command` (string, 必需)**: 要执行的命令行程序或脚本的路径（例如 `ls`, `python3`, `./my_script.sh`）。
  * **`args` (array of string, 可选)**: 传递给命令的参数数组。支持变量插值，例如 `"${directory}"`。
  * **`env` (object, 可选)**: 传递给命令的自定义环境变量。支持变量插值，例如 `"${directory}"`。
  * **`cwd` (string, 可选)**: 命令执行的工作目录。如果未指定，则默认为 `@pamcp/bridge` 进程的当前工作目录。支持变量插值。
  * **`inputSchema` (object, 必需)**: 一个JSON Schema对象，定义了此命令工具接受的输入参数。AI编辑器会根据此Schema生成调用参数。

#### `type: "api"` (REST API工具)

用于将HTTP RESTful API端点封装成MCP工具。

  * **`endpoint` (string, 必需)**: API请求的目标URL。支持变量插值，例如 `https://api.example.com/users/${user_id}`。
  * **`method` (string, 必需)**: HTTP请求方法（例如 `GET`, `POST`, `PUT`, `DELETE`）。
  * **`headers` (object, 可选)**: HTTP请求头键值对。例如 `{"Content-Type": "application/json", "Authorization": "Bearer ${token}"}`。支持变量插值。
  * **`body` (object/string, 可选)**: HTTP请求体。对于 `POST`, `PUT` 请求通常需要。支持嵌套对象和变量插值。如果 `Content-Type` 为 `application/json`，则会自动JSON序列化。
  * **`inputSchema` (object, 必需)**: 一个JSON Schema对象，定义了此API工具接受的输入参数。

#### 变量插值

在 `args`、`env`、`cwd`、`endpoint`、`headers` 和 `body` 字段中，您可以使用 `${variable_name}` 语法来引用在 `inputSchema` 中定义的参数。当AI调用工具时，它会根据 `inputSchema` 提供相应的参数值，这些值将自动替换掉插值占位符。

-----

## 📚 配置集示例

-----

有了 **@pamcp/bridge**，您可以轻松配置出属于自己的MCP服务配置集，将您的想法、本地工具或API接口变成强大的MCP服务，并轻松与他人共享。

以下是一些示例配置，您可以直接复制以下 URL 到@pamcp/bridge的 `--configUrl` 值中进行尝试

  * **Git 命令工具集**: 一组将常见Git操作（如 `git pull`、`git status`）封装成MCP工具的配置。
https://raw.githubusercontent.com/pamcp/bridge/refs/heads/main/examples/amap.json
    ```plaintext
    https://raw.githubusercontent.com/pamcp/bridge/refs/heads/main/examples/git.json
    ```

    [查看 Git 命令工具集](https://raw.githubusercontent.com/pamcp/bridge/refs/heads/main/examples/git.json)

  * **Hacker News 工具集**: 将Hacker News API封装成MCP工具，方便AI获取热门新闻或特定文章信息。

    ```plaintext
    https://raw.githubusercontent.com/pamcp/bridge/refs/heads/main/examples/hacker_news.json
    ```

    [查看 Hacker News 工具集](https://raw.githubusercontent.com/pamcp/bridge/refs/heads/main/examples/hacker_news.json)

  * **高德地图工具集**: 将高德地图API（如天气查询、地理编码）封装为MCP工具，方便AI获取地理位置信息。

    ```plaintext
    https://raw.githubusercontent.com/pamcp/bridge/refs/heads/main/examples/amap.json
    ```

    [查看 高德地图工具集](https://raw.githubusercontent.com/pamcp/bridge/refs/heads/main/examples/amap.json)

-----

## 🤝 贡献

我们欢迎并鼓励对 **@pamcp/bridge** 项目的贡献！无论您是想报告错误、提出新功能、改进文档还是提交代码，您的参与都将帮助我们做得更好。

请通过以下方式参与：

  * **报告问题**：如果您在使用过程中遇到任何问题或发现Bug，请在 [GitHub Issues](https://github.com/pamcp/bridge/issues) 提交。
  * **提交拉取请求 (PR)**：如果您有代码改进或新功能实现，请提交拉取请求。请确保您的代码符合项目规范，并提供清晰的描述。

-----

<!-- ## 许可证

该项目根据 MIT 许可证发布。有关更多详细信息，请参阅 [LICENSE](https://github.com/pamcp/bridge/blob/main/LICENSE) 文件。

----- -->

## 联系我们

如果您有任何疑问或建议，欢迎通过以下渠道联系我们：

  * **GitHub Issues**: [https://github.com/pamcp/bridge/issues](https://github.com/pamcp/bridge/issues)
  * **NPM**: [https://www.npmjs.com/package/@pamcp/bridge](https://www.npmjs.com/package/@pamcp/bridge)

感谢您使用 @pamcp/bridge！希望它能帮助您更高效地工作！