mcpField
C
CosmWasm MCP Server Template

CosmWasm MCP Server Template

本地服务
github.com/archway-network开发工具174 周前更新

关于 CosmWasm MCP Server Template

CosmWasm MCP Server Template 是用于通过 MCP 暴露 CosmWasm 合约查询和执行消息的 Rust 模板。开发者可替换合约依赖与部署地址,并生成供签名者广播的消息。

主要功能

  1. 01封装合约查询消息
  2. 02构建合约执行消息
  3. 03根据合约消息类型生成模式
  4. 04支持 stdio、SSE 和 HTTP streamable 传输
  5. 05可选暴露自定义查询响应

适用场景

  1. 01为 CosmWasm 合约创建 MCP 服务
  2. 02为签名钱包准备合约查询
  3. 03构建供钱包广播的交易

MCP 相关

该模板将合约查询和执行消息构建器作为 MCP 工具提供,支持 stdio、SSE 和 HTTP streamable 传输。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

暂未收录安装方式

我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。

代码仓库

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

CosmWasm MCP 服务模板

用于封装查询和执行入口消息的 Rust MCP 服务,这些消息可由签名者广播。此项目模板适用于任何 CosmWasm 合约。

构建此项目

构建此项目需要 Rust 的 nightly 版本,以便使用 rustc 的 edition 2024。

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

此项目是一个可用于任何 CosmWasm 合约的 MCP 服务模板,但要将此模板用于你自己的合约,需要做一些小改动。

要将此模板用于你自己的合约,请进行以下_必要_更改:

步骤 1 - 更新 Cargo.toml
  • 更改 Cargo.toml 中的合约依赖项

从 Cargo.toml 中移除以下行,并替换为你自己的合约依赖项:

cw20-wrap = { git = "https://github.com/archway-network/cw20-wrap.git", version = "1.0.0", features = ["library"] }
步骤 2 - 确保你的合约可以构建为库
  • 你_应该_确保刚添加到 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-wrap 依赖项,并替换为你自己的合约对应的依赖项。你的合约必须公开导出 msg::QueryMsg 和 msg::Execute,以便 MCP 服务能够创建 AI Agent 可理解的 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() 函数中的 contracts 数组移除对应项(查看代码)。

/// 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 工具
  • 如果你的合约使用了自定义类型或响应,并且你认为 AI Agent 能从中受益,可以参考 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(可选)- 自定义大模型指令
  • 系统提示词上下文的所有服务指令和工具描述都位于 src/instruction.rs 中。
  • src/instruction.rs 的内容是基础的可运行示例。处理复杂合约和/或多合约系统时,你可能需要完善工具和服务描述,为大模型提供更详细的上下文。
  • 关于如何改进大模型指令并根据你的合约进行定制,可参考 Ambur MCP server 中的 instruction.rs。
步骤 7(可选)- 设置 MCP 服务传输模式
  • 此模板支持 3 种传输模式:stdio、sse 和 http-streamable
  • 此模板默认使用 stdio 传输模式
  • 关于传输模式:
    • stdio - 服务端使用系统标准输入 / 输出进行响应
    • sse - 服务端事件服务(MDN 文档)
    • http-streamable - 适用于远程 MCP 服务的较新标准,可提供 JSON API 服务功能(Claudemcp 文档)
提升 AI 准确性

添加文档注释对生成 schema 非常重要

即使扩展了服务说明、工具描述和工具参数描述,你也可能发现 AI 仍会提供不准确或误导性的数据,或对合约入口点的说明不够详细。通常,这是因为合约源代码中的 msg::QueryMsg 和 msg::ExecuteMsg 缺少文档注释(例如三斜线注释 ///)。

这是因为 schemars 会将文档注释直接嵌入 schema,作为描述元数据字段。

下面是一个注释完善的 msg::QueryMsg 示例,可帮助引导 LLM Agent:

#[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 的 2 个变体会在生成的 schema 中嵌入以下描述,这对需要理解查询入口点的大模型非常有帮助:

[
    {
      "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. 完整的多合约示例,请参阅 Ambur 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 连接到 Claude Desktop

以下说明假设 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 用户,将虚拟机设为 command,并使用运行参数(args)指定虚拟机运行二进制文件的位置:

// 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-adapters。此包会将 MCP 端点转换为 Graph 工具。

使用 @langchain/mcp-adapters
// 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();
// ...

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。