MCP 服务开发到发布

环境

MCP服务开发环境需要Python 3.10+

我推荐使用uv工具管理Python环境 https://docs.astral.sh/uv/

这个创建一下标准的包结构, 还是比较方便

MCP 调试工具 : https://github.com/modelcontextprotocol/inspector

MCP 服务

官方文档: https://modelcontextprotocol.io/quickstart/server

MCP 服务

MCP主要通信方式:

  1. Stdio transport
    • Uses standard input/output for communication
    • Ideal for local processes
  2. Streamable HTTP transport
    • Uses HTTP with optional Server-Sent Events for streaming
    • HTTP POST for client-to-server messages

stdio:通过标准输入输出流传递数据,实现简单,兼容性强,适合本地开发测试。

sse:允许服务器向客户端推送实时更新,单向通信,适用于需要持续数据更新的场景如实时通知。

注:后来阅读文档, SSE的模式已经废弃了, 但还是很多人用

建立项目

mcp_requests % uv init . --package -p 3.13
Initialized project mcp-requests at /Users/xxxxx/Desktop/mcp_requests

mcp_requests % uv add “mcp[cli]”

在这里插入图片描述

简单代码, 帮我简单发一个 http 的 get 和post 这种方法

import json
from typing import Dict, Any, Optional
import httpx
from mcp.server.fastmcp import FastMCP

# Create an MCP server
mcp = FastMCP("HTTP Requests")

@mcp.tool()
def http_get(url: str, headers: Optional[Dict[str, str]] = None) -> str:
    """Make an HTTP GET request"""
    try:
        with httpx.Client() as client:
            response = client.get(url, headers=headers or {})
            return json.dumps({
                "status_code": response.status_code,
                "headers": dict(response.headers),
                "content": response.text
            }, indent=2)
    except Exception as e:
        return f"Error: {str(e)}"

@mcp.tool()
def http_post(url: str, data: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None) -> str:
    """Make an HTTP POST request"""
    try:
        with httpx.Client() as client:
            response = client.post(url, json=data, headers=headers or {})
            return json.dumps({
                "status_code": response.status_code,
                "headers": dict(response.headers),
                "content": response.text
            }, indent=2)
    except Exception as e:
        return f"Error: {str(e)}"

@mcp.tool()
def http_put(url: str, data: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None) -> str:
    """Make an HTTP PUT request"""
    try:
        with httpx.Client() as client:
            response = client.put(url, json=data, headers=headers or {})
            return json.dumps({
                "status_code": response.status_code,
                "headers": dict(response.headers),
                "content": response.text
            }, indent=2)
    except Exception as e:
        return f"Error: {str(e)}"

@mcp.tool()
def http_delete(url: str, headers: Optional[Dict[str, str]] = None) -> str:
    """Make an HTTP DELETE request"""
    try:
        with httpx.Client() as client:
            response = client.delete(url, headers=headers or {})
            return json.dumps({
                "status_code": response.status_code,
                "headers": dict(response.headers),
                "content": response.text
            }, indent=2)
    except Exception as e:
        return f"Error: {str(e)}"

def main() -> None:
    import asyncio
    asyncio.run(mcp.run(transport='stdio'))

if __name__ == "__main__":
    main()

尝试本地测试调用, 再 cursor (其他也可以,我只是电脑恰好有, 比较方便) 里面添加服务,

{
  "mcpServers": {
    "request-server-aaddb": {
      "name": "request-mcp-server-aaddb",
      "type": "stdio",
      "description": "AADDb MCP server",
      "isActive": true,
      "command": "uv",
      "args": ["--directory",
"/Users/yi.zhai/Desktop/mcp_requests", "run", "mcp-requests"]
    }
  }
}

成功启动

在这里插入图片描述
在这里插入图片描述

尝试让 AI 调用

服务成功收到请求, 测试成功, 功能是跑通了

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

PyPI 上传步骤总结

安装构建工具

uv add build twine

构建

uv run python -m build

上传

uv run python -m twine upload dist/* -u **token** -p pypi-xxxxxx

成功标志:

在这里插入图片描述

最后尝试一下 ,直接导入使用, 没问题

{
  "mcpServers": {
    "mcp-request": {
      "command": "mcp-request",
      "type": "stdio"
    }
  }
}

在这里插入图片描述

最后文档服务发布到了

https://pypi.org/project/mcp-request/ 大家可以试试

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐