自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

MCP協(xié)議之MCP-server(sse方式)實踐 原創(chuàng)

發(fā)布于 2025-4-3 10:50
瀏覽
0收藏

背景

在《MCP協(xié)議簡述之MCP-server實戰(zhàn)》中,我們實現(xiàn)了一個本地的MCP-server,然后在支持MCP協(xié)議的客戶端程序(如cursor、cherry-studio)中配置調(diào)用了該MCP-server。本章主要探索如何將MCP-server發(fā)布為遠程服務,使得其他用戶可以直接使用MCP-server。

回顧問題

在上一章,我們在cherry-studio中配置了獲取天氣的本地mcp-server,關(guān)鍵配置如下:

{
    "mcpServers":{
        "weather":{
            "command":"/Users/deadwalk/.local/bin/uv",
            "args":[
                "--directory",
                "/Users/deadwalk/Code/ai_proj_agent/weather",
                "run",
                "weather.py"
            ]
        }
    }
}

這種方式的主要問題是:weather這個mcp-server是本地的,只有當前本地用戶才能使用,網(wǎng)絡上的其他用戶是無法使用的。

解決方案

我們需要將MCP-server進行改造,使得其他用戶可以直接使用。

MCP-server改造前的實現(xiàn)

  1. 導入包并設置實例

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

# 初始化FastMCP服務器
mcp = FastMCP("weather")

# 常量
BAIDU_API_BASE = "https://api.map.baidu.com/weather/v1/"
BAIDU_API_KEY = "8HkEwz5h********"
  1. 實現(xiàn)入口函數(shù)的部分

if __name__ == "__main__":
    # 初始化并運行服務器
    mcp.run(transport='stdio')

MCP-server源碼分析

通過查看FastMCP的源碼,可以看到FastMCP在實例化對象的時候,是可以配置setting的

class FastMCP:
    def __init__(
        self, name: str | None = None, instructions: str | None = None, **settings: Any
    ):
        self.settings = Settings(**settings)        #  這里就是設置實例的設置

        self._mcp_server = MCPServer(
            name=name or "FastMCP",
            instructions=instructions,
            lifespan=lifespan_wrapper(self, self.settings.lifespan)
            if self.settings.lifespan
            else default_lifespan,
        )
    # 以下內(nèi)容省略

進一步查看settings的源碼,可以看到setting中可以配置host、port\message_path\lifespan等參數(shù)。

class Settings(BaseSettings, Generic[LifespanResultT]):
    """FastMCP server settings.

    All settings can be configured via environment variables with the prefix FASTMCP_.
    For example, FASTMCP_DEBUG=true will set debug=True.
    """

    model_config = SettingsConfigDict(
        env_prefix="FASTMCP_",
        env_file=".env",
        extra="ignore",
    )

    # Server settings
    debug: bool = False
    log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "ERROR"

    # HTTP settings
    host: str = "0.0.0.0"
    port: int = 8000
    sse_path: str = "/sse"
    message_path: str = "/messages/"

    # resource settings
    warn_on_duplicate_resources: bool = True

    # tool settings
    warn_on_duplicate_tools: bool = True

    # prompt settings
    warn_on_duplicate_prompts: bool = True

    dependencies: list[str] = Field(
        default_factory=list,
        description="List of dependencies to install in the server environment",
    )

    lifespan: (
        Callable[[FastMCP], AbstractAsyncContextManager[LifespanResultT]] | None
    ) = Field(None, description="Lifespan context manager")

MCP-server改造后的實現(xiàn)

  1. 導入包并設置實例

from typing importAny, Dict
import httpx
from mcp.server.fastmcp import FastMCP

# 初始化FastMCP服務器
# mcp = FastMCP("weather")
mcp = FastMCP(
    name="weather",
    host="0.0.0.0",
    port=8000,
    description="獲取指定城市的當前天氣信息",
    sse_path='/sse'
)

# 常量
BAIDU_API_BASE = "https://api.map.baidu.com/weather/v1/"
BAIDU_API_KEY = "8HkEwz5h********"

2. 實現(xiàn)入口函數(shù)的部分

if __name__ == "__main__":
    # 初始化并運行服務器
    try:
        print("Starting server...")
        mcp.run(transport='sse')
    except Exception as e:
        print(f"Error: {e}")

3. 在命令行中啟動服務

uv run weather.py

客戶端中使用

1. 在cherry-studio中集成使用

在局域網(wǎng)另外一臺機器上,打開cherry-studio的配置,在MCP服務中配置連接如下;

{
  "mcpServers": {
    "weather_demo": {
      "description": "這是一個weather的demo",
      "isActive": true,
      "baseUrl": "http://192.168.6.164:8000/sse"
    }
  }
}

備注:

  • 192.168.6.164是mcp-server的ip地址,端口為8000
  • 由于我們使用的是sse協(xié)議,所以需要將baseUrl設置為sse協(xié)議,即http://192.168.6.164:8000/sse

實際實驗效果:

MCP協(xié)議之MCP-server(sse方式)實踐-AI.x社區(qū)

2. 在cursor中集成使用

{
  "mcpServers": {
    "weather": {
      "url": "http://192.168.6.164:8000/sse"
    }
  }
    
}

實際實驗效果:

MCP協(xié)議之MCP-server(sse方式)實踐-AI.x社區(qū)

3. 在cline中集成使用

在cline中嘗試了多種方式配置,均未能成功,在github中找到了相應的issue,可能需要關(guān)注該項目后續(xù)的修復進展。

總結(jié)

  • 通過對mcp-server的改造,在實例化mcp-server的時候,配置相應的host、port,可以實現(xiàn)sse協(xié)議的部署。
  • 通過服務部署之后,其他用戶可以在支持mcp的客戶端中,通過mcp-server的url進行調(diào)用。

?

本文轉(zhuǎn)載自公眾號一起AI技術(shù) 作者:熱情的Dongming

原文鏈接:??https://mp.weixin.qq.com/s/MPHvQq-1TUT2jKNGPGZ02g??

?著作權(quán)歸作者所有,如需轉(zhuǎn)載,請注明出處,否則將追究法律責任
收藏
回復
舉報
回復
相關(guān)推薦