LangGraph 第三课:接入 MCP

在 Cline 和阿里云百炼里试接 MCP,再各写一遍 SSE 和 STDIO 示例。

LangGraph 第三课:接入 MCP
文章目录
  1. 一、用 Cline 接入 MCP
  2. 二、在阿里云百炼试用 MCP
  3. 三、SSE 和 STDIO 怎么工作
  4. SSE:
  5. 四、把 MCP 接到 LangGraph 的 Agent
  6. 五、自己写一个 MCP 服务

一、用 Cline 接入 MCP

这里用的是 IDEA 里的 Cline 插件。

文章配图

文章配图

二、在阿里云百炼试用 MCP

文章配图

开通高德地图的 MCP 服务。

文章配图

三、SSE 和 STDIO 怎么工作

SSE:

{
"mcpServers": {
	"amap-amap-sse": {
		 "url": "https://mcp.amap.com/sse?key=APIkey"
		}
	}
}

本地运行的例子需要先装 Node.js。通过 npx 启动程序后,就能取得高德地图的数据。

  • SSE 走 HTTP 长连接,由服务端单向推送数据。以高德地图为例,客户端和它的 HTTP 服务保持连接取数据,长期保持连接会给服务端带来压力。
  • STDIO 在客户端本地启动程序,从进程里读结果。程序由 MCP 服务提供者编写,运行时有机会操作客户端机器。

四、把 MCP 接到 LangGraph 的 Agent

用 langchain-mcp-adapters 连接服务。

import asyncio
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from config.load_key import load_key
from langchain_community.chat_models import ChatTongyi
from langchain_mcp_adapters.tools import load_mcp_tools

async def main():
    # 构建阿里云百炼大模型客户端
    llm = ChatTongyi(
        model="qwen-plus",
        api_key=load_key("API-KEY")
    )
    client = MultiServerMCPClient(
        {
            # "amap-amap-sse": {
        #     "url": "https://mcp.amap.com/v1/streaming",
        #     "transport": "streamable_http"
        # },
            "amap-maps": {
                "command": "npx",
                "args": [
                    "-y",
                    "@amap/amap-maps-mcp-server"
                ],
                "env": {
                    "AMAP_MAPS_API_KEY": "YOUR_AMAP_API_KEY"
                },
                "transport": "stdio"
            }
        }
    )
    async with client.session("amap-maps") as session:
        tools = await load_mcp_tools(session)

    agent = create_react_agent(
        model=llm,
        tools=tools
    )
    response = await agent.invoke(
        {
            "messages": [{"role": "user", "content": "帮我查一下北京到上海的航班"}]
        }
    )
    print(response)

# 执行异步主函数
asyncio.run(main())

五、自己写一个 MCP 服务

https://modelcontextprotocol.github.io/python-sdk/ 新建 Python 文件 mcp_server.py。

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("roymcpdemo")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers."""
    print(f"roy mcp demo called : add({a}, {b})")
    return a + b

@mcp.tool()
def weather(city: str) -> str:
    """Get the weather for a city."""
    print(f"roy mcp demo called : weather({city})")
    return f"The weather in {city} is sunny."

@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
    """Get a greeting for a name."""
    print(f"roy mcp demo called : greeting({name})")
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run(transport="sse")

    #mcp.run(transport="stdio")

文章配图

文章配图

前面的例子用 SSE。这里换成 STDIO。

from mcp import StdioServerParameters,stdio_client,ClientSession
import mcp.types as types


server_params = StdioServerParameters(
    command="python",
    args=["/path/to/mcp_server.py"],
    env=None
)
async def handle_sampling_message(message: types.CreateMessageRequestParams) -> types.CreateMessageResult:
    print(f"Received sampling message: {message}")
    return types.CreateMessageResult(
        role="assistant",
        content=types.TextContent(
            type="text",
            text="This is a response from the client."
        ),
        model="gpt-3.5-turbo",
        stopReason="endTurn"
    )

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read,write,sampling_callback=handle_sampling_message) as session:
            await session.initialize()

            prompts = await session.list_prompts()
            print(f"prompts: {prompts}")

            tools = await session.list_tools()
            print(f"tools: {tools}")

            resources = await session.list_resources()
            print(f"resources: {resources}")

            result = await session.call_tool("weather", {"city": "New York"})
            print(f"result: {result}")

if __name__ == "__main__":
    import asyncio
    asyncio.run(run())

客户端调用刚才的 server.py。

python /path/to/mcp_client.py
prompts: meta=None nextCursor=None prompts=[]
tools: meta=None nextCursor=None tools=[Tool(name='add', title=None, description='Add two numbers.', inputSchema={'properties': {'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}, 'required': ['a', 'b'], 'title': 'addArguments', 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'integer'}}, 'required': ['result'], 'title': 'addOutput', 'type': 'object'}, icons=None, annotations=None, meta=None), Tool(name='weather', title=None, description='Get the weather for a city.', inputSchema={'properties': {'city': {'title': 'City', 'type': 'string'}}, 'required': ['city'], 'title': 'weatherArguments', 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'string'}}, 'required': ['result'], 'title': 'weatherOutput', 'type': 'object'}, icons=None, annotations=None, meta=None)]
resources: meta=None nextCursor=None resources=[]
result: meta=None content=[TextContent(type='text', text='The weather in New York is sunny.', annotations=None, meta=None)] structuredContent={'result': 'The weather in New York is sunny.'} isError=False
[10/13/25 21:21:16] INFO     Processing request of type            server.py:664
                             ListPromptsRequest
                    INFO     Processing request of type            server.py:664
                             ListToolsRequest
                    INFO     Processing request of type            server.py:664
                             ListResourcesRequest
                    INFO     Processing request of type            server.py:664
                             CallToolRequest

Process finished with exit code 0

服务端文件也要切换到 STDIO 模式。

评论

暂时没有评论。