CosmWasm MCP服务器模板

一个用于包装查询和执行入口点消息的Rust MCP服务器模板,适用于任何CosmWasm合约,支持多种传输模式和AI工具集成。

  • by drewstaylor
  • Rust
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 drewstaylor/cosmwasm-mcp-template

使用说明

CosmWasm MCP服务器模板

Rust中的MCP服务器,用于包装查询并执行签名者要广播的入口点消息。此项目模板应适用于任何CosmWasm合同。

构建此项目

要构建此项目,需要 nightly Rust的构建,这将允许使用rustc的2024版。

# Switch rustc to `nightly` channel
rustup default nightly
# Build for development
cargo build
# Build for deployment
cargo build --release

如何使用

此项目是一个MCP服务器模板,可用于任何CosmWasm合约,但要将此模板用于您自己的合约,您需要进行一些小的更改。

要将此模板用于您自己的合同,请执行以下操作 强制性的 变化:

步骤1-更新Cargo.toml

  • 更改中的合同依赖关系 Cargo.toml

删除以下行 Cargo.toml 并将其替换为合同的依赖关系:

cw20-wrap = { git = "https://github.com/archway-network/cw20-wrap.git", version = "1.0.0", features = ["library"] }

第二步-确保你的合同可以构建为一个库

  • 你 应该 确保您刚才添加到的依赖关系 Cargo.toml 不出口 cosmwasm_std::entry_point, query 和 execute.

例如,你的合同应该 不 导入 entry_point, query 和 execute (以此类推 instantiate, reply, migrate等与您的项目相关),如下所示:

use cosmwasm_std::{
    entry_point, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult,
    Uint128,
};
// ...
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> Result<Response, ContractError> {
    // ...
}
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
    // ...
}

相反,你应该像这样展示你的合同入口点:

#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
    to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult,
    Uint128,
};
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> Result<Response, ContractError> {
    // ...
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
    // ...
}

步骤3-更新server.rs

  • 更改中的合同依赖关系 src/server.rs

在顶部 src/server.rs 文件(查看代码),删除默认值 cw20包装 依赖关系,并将其替换为您的合约的相应依赖关系。您的合同必须公开导出 msg::QueryMsg 和 msg::Execute MCP服务器能够创建AI代理可以理解的JSON模式。

/// Replace the below import with the contract you want the MCP server to support
use cw20_wrap::msg::{ExecuteMsg, QueryMsg};

步骤4-更新contract.rs中已部署的合约地址

最底层 src/contract.rs (查看代码),更新合约的主网和测试网部署的已部署合约地址。或者,如果你想删除其中一个条目,所以只有一个测试网或一个主网条目,你需要从合约数组中删除该条目 CwMcp::new() 功能(查看代码).

/// Replace with your deployed contract addresses.
/// This helps the query msg and tx msg builders wrap
/// your query and tx messages to the contract into
/// CosmWasm's `QueryRequest` and `CosmosMessage` types
/// that can be broadcast by a rpc enabled wallet tool
pub static CONTRACT_MAINNET: &str =
    "archway1gaf9nw7n8v5lpjz9caxjpps006kxfcrzcuc8y5qp4clslhven2ns2g0ule";
pub static CONTRACT_TESTNET: &str =
    "archway1r8kepegwhldwqanuurc769l2g0qxlsm2sm6t5rhqjzcerxsgshls267f7a";

步骤5(可选)-为任何自定义类型启用MCP工具

  • 如果你的合同使用了你认为对人工智能代理应该访问有益的任何自定义类型或响应,那么有一个例子(注释掉了) server.rs 如何实现这一点(见下面的摘录 src/server.rs).
/// (Optionally) if your contract provides any custom query response types
/// configure this tool so the MCP agent can access them. Allowing the MCP
/// agent to access the custom query responses enables it to provide smarter
/// advice, and summaries, about exacly what data can be fetched when making
/// a query to the contract.
/// @see: src/query.rs
#[tool(description = LIST_QUERY_RESPONSE_DESCR)]
async fn list_query_responses(&self) -> Result<CallToolResult, Error> {
    let schema = schema_for!(AllQueryResponse);
    let serialized: String = serde_json::to_string(&schema).unwrap_or("".to_string());
    Ok(CallToolResult::success(vec![Content::text(serialized)]))
}

步骤6(可选)-自定义LLM指令

  • 系统提示上下文的所有服务器指令和工具描述都位于 src/instruction.rs.
  • 内容 src/instruction.rs 这些都是基本的工作示例。当处理复杂的合约和/或多合约系统时,您可能需要改进工具和服务器描述,为LLM提供更详细的上下文。
  • 有关如何改进LLM指令并使其针对您的合同进行定制的示例,请查看 指令.rs 从 救护车MCP服务器.

步骤7(可选)-设置MCP服务器传输模式

  • 此模板支持3种传输模式:stdio、sse和http流式传输
  • 此模板默认为stdio传输模式
  • 关于运输方式:
    • 标准 -服务器将使用系统标准输入/输出进行响应
    • SSE -服务器端事件服务器(MDN文档)
    • http流媒体 -远程MCP服务器的更新标准,提供JSON API服务器功能(Claudemcp文件)

优化AI准确性

在您的文档中添加文档注释对于模式生成很重要

即使在扩展了您的服务器说明、工具描述和工具参数描述后,您也可能会发现AI继续提供不准确或误导性的数据,或者很少提供有关合同切入点的详细信息。通常,这是由于您的合同源代码中缺少文档注释(例如三斜线注释“///”) msg::QueryMsg 和 msg::ExecuteMsg

这是因为 阴谋家 将文档注释作为描述元数据字段直接嵌入到模式中。

这里有一个评论很好的例子 msg::QueryMsg 这将有助于指导LLM代理:

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    /// Get all swaps (enumerable)
    /// Return type: ListResponse
    List {
        start_after: Option<String>,
        limit: Option<u32>,
    },
    /// Get all Collection Offers (enumerable)
    /// Return type: ListResponse
    ListCollectionOffers {
        start_after: Option<String>,
        limit: Option<u32>,
    },
    // ...
}

上述两种变体 QueryMsg 将在生成的模式中生成以下嵌入式描述,这对需要解释查询入口点的LLM非常有帮助:

[
    {
      "description": "Get all swaps (enumerable) Return type: ListResponse",
      "type": "object",
      "required": [
        "list"
      ],
      // ... 
    },
    {
      "description": "Get all Collection Offers (enumerable) Return type: ListResponse",
      "type": "object",
      "required": [
        "list_collection_offers"
      ],
      // ...
    },
]

多合同系统

  • 有时,构建一个支持多个合约的MCP服务器是有意义的。实现这一目标的战略是直截了当的:
  1. 为合同命名空格(例如,以避免重复的符号导入)
  2. 实现模式匹配和工具参数,以在不同合约之间进行切换
  3. 有关完整的多合约示例,请参阅 救护车MCP服务器

此MCP服务器模板提供的工具

默认情况下,此MCP服务器提供以下6个工具和功能。

  1. list_contract_deployments -列出Ambur核心合约地址(主网和测试网)
  2. list_nft_collections -列出Ambur NFT(主网和测试网合约地址、集合名称和集合描述)
  3. list_query_entry_points -列出可以对核心Ambur市场合同进行的查询
  4. build_query_msg -构建对核心Ambur市场合约的查询,该合约可以通过RPC连接的钱包进行广播
  5. list_tx_entry_points -列出可以对核心Ambur市场合同进行的交易
  6. build_execute_msg -构建一个交易到核心Ambur市场合约,该合约可以由RPC连接的钱包签名和广播

将MCP连接到克劳德桌面

以下说明假设MCP服务器是内置的 stdio 模式(这是为Claude桌面配置最简单的模式)。

构建一个发布二进制文件,并指向mcp服务器 command 走自己的路。无运行参数(args)需要:

// claude_desktop_config.json
{
  "mcpServers": {
    "ambur": {
      "command": "/your-computer-path/cosmwasm-mcp-template/target/release/cosmwasm-mcp-template",
      "args": []
    }
  }
}

对于虚拟机设置和WSL用户,请按以下方式执行VM command 并使用run参数(args)指向VM运行二进制文件的位置:

// claude_desktop_config.json
{
  "mcpServers": {
    "ambur": {
      "command": "wsl.exe",
      "args": [
        "bash",
        "-ic",
        "/your-vm-path/cosmwasm-mcp-template/target/release/cosmwasm-mcp-template",
      ]
    }
  }
}

将MCP连接到LangGraph

@langchain/mcp适配器 必须安装在图形项目中。此包将把MCP端点转换为Graph工具。

使用@langchain/mcp适配器

// graph.ts
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
// ...
// Create client and connect to server
const client = new MultiServerMCPClient({
  throwOnLoadError: true,
  prefixToolNameWithServerName: true,
  additionalToolNamePrefix: "mcp",
  mcpServers: {
    cosmwasm_contract: {
      transport: "sse",
      url: "http://localhost:8000", // Or, URL + IP of a remote host
      useNodeEventSource: true,
      reconnect: {
        enabled: true,
        maxAttempts: 5,
        delayMs: 2000,
      },
      // Or, uncomment to use transport mode `http-streamable`:
      // url: "http://localhost:8000",
      // headers: {},
      // automaticSSEFallback: false
    },
  },
});

const tools = await client.getTools();
// ...