目录
Model Context Protocol 样例
/    

Model Context Protocol 样例

Model Context Protocol

模型上下文协议,服务于LLM,调用外部数据。例如:天气数据、数据库数据等等。

  • 工具列表、工具调用
  • 资源列表、获取资源
  • 提示词列表,获取提示词

示例代码

完整代码:https://github.com/MrNiebit/hot-topic-mcp

调试服务端也可以使用命令 mcp dev xxx-server.py

服务端代码

from mcp.server.lowlevel.server import Server, NotificationOptions
from mcp.server.models import InitializationOptions
from mcp.server.stdio import stdio_server
import mcp.types as types
from items.hot_topic_factory import HotTopicFactory
import json


server = Server("hot-topic-mcp")

TOOLS = [
    types.Tool(
        name="sina_weibo_hot_topic",
        description="这是一个用来获取新浪微博热搜的工具",
        inputSchema={
            "type": "object",
            "properties": {
                "top": {
                    "type": "integer",
                    "description": "热搜的数量",
                    "default": 10
                }
            }
        }
    )
]
TOOLS_NAME_LIST = {tool.name: tool for tool in TOOLS}

@server.list_tools()
async def list_tools() -> list[types.Tool]:
    return TOOLS


@server.call_tool()
async def call_tool(name: str, arguments: dict | None) -> list[types.TextContent]:
    if name not in TOOLS_NAME_LIST:
        raise ValueError("未找到对应的工具")
    # print(arguments)
    result = HotTopicFactory.get_hot_topics(name, **arguments)

    # 这里返回的是列表
    return [types.TextContent(
        type="text",
        text=json.dumps(result, ensure_ascii=False)
    )]


async def run():
    async with stdio_server() as (read, write):
        await server.run(
            read_stream=read,
            write_stream=write,
            initialization_options=InitializationOptions(
                server_name="host-topic-mcp",
                server_version="2025.03.16",
                capabilities=server.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={}
                )
            )
        )


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

单元测试代码

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client

server_params = StdioServerParameters(
    command="python",
    args=["../main.py"]
)

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # 初始化
            print(await session.initialize())
            result = await session.list_tools()
            print(result)

            result = await session.call_tool(name="sina_weibo_hot_topic", arguments={"top": 5, "type": "all"})
            print(result)



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

使用效果

这里使用 Claude Desktop App 测试的,Cherry-Studio、vscode的Cline插件这些也都是支持的。

image.png

LLM调用MCP示例

代码:https://github.com/MrNiebit/llm-mcp-invoke


标题:Model Context Protocol 样例
作者:gitsilence
地址:https://blog.lacknb.cn/articles/2025/03/16/1742122259808.html