最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python從零構(gòu)建一個(gè)MCP服務(wù)器

 更新時(shí)間:2025年08月22日 08:23:00   作者:站大爺IP  
MCP協(xié)議定義了一套標(biāo)準(zhǔn)化通信機(jī)制,讓AI代理能動(dòng)態(tài)發(fā)現(xiàn)并調(diào)用服務(wù)器上的工具函數(shù),所以本文將使用Python構(gòu)建一個(gè)簡單的MCP服務(wù)器,感興趣的小伙伴可以了解下

一、MCP協(xié)議:AI與工具的"USB-C接口"

想象你正在用AI助手處理工作:需要查詢天氣時(shí),AI突然彈出"我需要調(diào)用天氣API"的提示;處理Excel數(shù)據(jù)時(shí),它又卡在"如何讀取CSV文件"的步驟。傳統(tǒng)AI的局限性在于,它像一臺沒有外設(shè)的電腦——能思考卻無法操作現(xiàn)實(shí)世界。

MCP(Model Context Protocol)協(xié)議的出現(xiàn)解決了這個(gè)痛點(diǎn)。它定義了一套標(biāo)準(zhǔn)化通信機(jī)制,讓AI代理(如Claude、Cursor)能動(dòng)態(tài)發(fā)現(xiàn)并調(diào)用服務(wù)器上的工具函數(shù)。就像給電腦插上USB-C線,AI瞬間獲得了訪問數(shù)據(jù)庫、調(diào)用API、操作文件系統(tǒng)的能力。

核心價(jià)值:

  • 解耦設(shè)計(jì):工具函數(shù)與AI模型分離,修改工具不影響模型訓(xùn)練
  • 安全沙箱:通過服務(wù)器中轉(zhuǎn)調(diào)用,避免直接暴露API密鑰
  • 統(tǒng)一入口:用標(biāo)準(zhǔn)化協(xié)議整合分散的工具接口

二、環(huán)境搭建:3分鐘啟動(dòng)開發(fā)環(huán)境

創(chuàng)建隔離環(huán)境

# 使用uv工具快速初始化項(xiàng)目(推薦)
uv init mcp_weather_server && cd mcp_weather_server
uv venv && source .venv/bin/activate  # Linux/Mac
# 或 .venv\Scripts\activate (Windows)

安裝核心依賴

# 基礎(chǔ)版(適合個(gè)人開發(fā))
uv add mcp>=1.9.1 requests python-dotenv
 
# 企業(yè)版(需處理高并發(fā))
uv add fastmcp httpx uvicorn[standard]

驗(yàn)證安裝

# 創(chuàng)建test_install.py
from mcp.server.fastmcp import FastMCP
print("MCP SDK安裝成功" if 'FastMCP' in globals() else "安裝失敗")

運(yùn)行 python test_install.py 應(yīng)輸出成功信息。

三、工具開發(fā):讓AI可調(diào)用的"魔法函數(shù)"

案例1:實(shí)時(shí)天氣查詢工具

# weather_tool.py
import requests
from mcp.server.fastmcp import tool
from dotenv import load_dotenv
import os
 
load_dotenv()  # 加載環(huán)境變量
 
@tool()
def get_weather(city: str) -> dict:
    """獲取城市實(shí)時(shí)天氣(需配置API_KEY)
    
    Args:
        city: 城市名稱(如"北京")
    
    Returns:
        包含溫度、濕度、天氣狀況的字典
    """
    api_key = os.getenv('WEATHER_API_KEY')
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    
    try:
        response = requests.get(url, timeout=5)
        data = response.json()
        return {
            "temperature": data["main"]["temp"],
            "humidity": data["main"]["humidity"],
            "condition": data["weather"][0]["description"]
        }
    except Exception as e:
        return {"error": f"天氣查詢失敗: {str(e)}"}

關(guān)鍵設(shè)計(jì)原則:

  • 類型注解:用 city: str 明確參數(shù)類型
  • 錯(cuò)誤處理:捕獲網(wǎng)絡(luò)請求異常
  • 文檔字符串:詳細(xì)說明參數(shù)和返回值
  • 環(huán)境變量:敏感信息(如API密鑰)通過 .env 文件管理

案例2:數(shù)據(jù)庫查詢工具

# db_tool.py
import sqlite3
from mcp.server.fastmcp import tool
from mcp.types import TableContent
 
@tool()
def query_sales_data(limit: int = 10) -> TableContent:
    """查詢銷售數(shù)據(jù)表(示例用)
    
    Args:
        limit: 返回記錄數(shù)上限
    
    Returns:
        表格數(shù)據(jù)(包含列名和行數(shù)據(jù))
    """
    conn = sqlite3.connect("sales.db")
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM orders LIMIT {limit}")
    
    columns = [desc[0] for desc in cursor.description]
    rows = cursor.fetchall()
    
    return TableContent(
        type="table",
        columns=columns,
        rows=rows
    )

企業(yè)級優(yōu)化:

  • 使用參數(shù)化查詢防止SQL注入
  • 添加連接池管理數(shù)據(jù)庫連接
  • 通過Nacos動(dòng)態(tài)配置數(shù)據(jù)庫地址

四、服務(wù)器構(gòu)建:3種通信模式詳解

模式1:本地開發(fā)模式(stdio)

# server_stdio.py
from mcp.server.fastmcp import FastMCP
from weather_tool import get_weather
from db_tool import query_sales_data
 
mcp = FastMCP("Local Tools Server")
mcp.add_tool(get_weather)
mcp.add_tool(query_sales_data)
 
if __name__ == "__main__":
    mcp.run(mode="stdio")  # 通過標(biāo)準(zhǔn)輸入輸出通信

適用場景:

  • 與Claude Desktop/Cursor本地集成
  • 快速驗(yàn)證工具功能
  • 開發(fā)階段調(diào)試

模式2:云端部署模式(SSE)

# server_sse.py
from fastmcp import FastMCP
from weather_tool import get_weather
import uvicorn
 
mcp = FastMCP("Cloud Tools Server")
mcp.add_tool(get_weather)
 
if __name__ == "__main__":
    # 通過HTTP事件流通信
    uvicorn.run(
        mcp.as_app(),  # 轉(zhuǎn)換為FastAPI應(yīng)用
        host="0.0.0.0",
        port=8000,
        workers=4  # 多進(jìn)程處理并發(fā)請求
    )

關(guān)鍵配置:

  • 添加JWT認(rèn)證中間件
  • 設(shè)置CORS允許前端調(diào)用
  • 配置Nginx反向代理

模式3:自動(dòng)化遷移模式(OpenAPI轉(zhuǎn)換)

# converter.py
import json
from jsonschema import validate
 
def convert_to_mcp_tool(api_spec):
    """將OpenAPI接口轉(zhuǎn)換為MCP工具
    
    Args:
        api_spec: OpenAPI規(guī)范字典
    
    Returns:
        MCP工具代碼模板字符串
    """
    tool_template = f"""
@tool()
def {api_spec["operationId"]}(**kwargs):
    """
    {api_spec["summary"]}
    
    Parameters:
        {json.dumps(api_spec["parameters"], indent=4)}
    """
    # 這里添加實(shí)際調(diào)用邏輯
    return盛{{}}
    """
    return tool_template
 
# 示例:轉(zhuǎn)換天氣API
weather_api = {
    "operationId": "get_weather",
    "summary": "獲取城市天氣信息",
    "parameters": [
        {"name": "city", "in": "query", "required": True, "type": "string"}
    ]
}
print(convert_to_mcp_tool(weather_api))

企業(yè)應(yīng)用:

  • 批量遷移現(xiàn)有RESTful API
  • 生成標(biāo)準(zhǔn)化工具文檔
  • 與Higress網(wǎng)關(guān)集成實(shí)現(xiàn)協(xié)議轉(zhuǎn)換

五、AI集成:讓Claude調(diào)用你的工具

1.配置Claude Desktop

編輯配置文件 claude_desktop_config.json:

{
  "mcpServers": {
    "weather_service": {
      "command": "python",
      "args": ["server_stdio.py", "--mode", "stdio"]
    }
  }
}

2.自然語言調(diào)用示例

當(dāng)用戶在Claude中輸入:

"查詢北京今天的天氣"

AI內(nèi)部處理流程:

發(fā)現(xiàn)可用的 get_weather 工具

將自然語言轉(zhuǎn)換為工具調(diào)用:

{
  "toolName": "get_weather",
  "arguments": {"city": "北京"}
}

執(zhí)行工具并返回結(jié)果:

{
  "temperature": 28,
  "humidity": 65,
  "condition": "多云"
}

將結(jié)果生成自然語言回復(fù):

"北京今天氣溫28℃,濕度65%,天氣多云"

3.調(diào)試技巧

使用MCP Inspector可視化調(diào)試:

npx @modelcontextprotocol/inspector python server_stdio.py

瀏覽器打開 http://localhost:3000 可實(shí)時(shí)查看:

  • 工具注冊情況
  • 請求/響應(yīng)數(shù)據(jù)流
  • 調(diào)用耗時(shí)統(tǒng)計(jì)

六、安全與性能優(yōu)化

安全防護(hù)三板斧

敏感信息隔離:

# 使用Vault管理密鑰
from hvac import Client
 
def get_secret(path: str) -> str:
    client = Client(url="http://vault-server:8200")
    return client.secrets.kv.v2.read_secret_version(path=path)["data"]["data"]["key"]

參數(shù)校驗(yàn):

from pydantic import BaseModel, conint
 
class QueryParams(BaseModel):
    limit: conint(ge=1, le=100)  # 限制1-100的整數(shù)
 
@tool()
def safe_query(params: QueryParams) -> dict:
    validated = params.dict()  # 自動(dòng)校驗(yàn)參數(shù)
    # 執(zhí)行查詢邏輯...

執(zhí)行超時(shí)控制:

from functools import partial
import asyncio
 
async def timed_fetch(url: str, timeout: float = 5.0):
    try:
        return await asyncio.wait_for(requests.get(url), timeout=timeout)
    except asyncio.TimeoutError:
        return {"error": "請求超時(shí)"}

性能優(yōu)化方案

緩存策略:

from functools import lru_cache
 
@lru_cache(maxsize=100)
@tool()
def cached_weather(city: str) -> dict:
    # 首次調(diào)用執(zhí)行實(shí)際查詢
    # 后續(xù)調(diào)用直接返回緩存結(jié)果
    return _real_weather_query(city)

異步處理:

@tool()
async def async_data_processing(file_url: str):
    async with httpx.AsyncClient() as client:
        file_content = await client.get(file_url)
        # 并行處理數(shù)據(jù)...

水平擴(kuò)展:

# 使用Gunicorn部署FastMCP應(yīng)用
gunicorn server_sse:app -w 8 -k uvicorn.workers.UvicornWorker

七、完整項(xiàng)目示例:股票數(shù)據(jù)查詢系統(tǒng)

項(xiàng)目結(jié)構(gòu)

stock_mcp/
├── .env                # API密鑰配置
├── tools/
│   ├── __init__.py
│   ├── stock_api.py    # 股票查詢工具
│   └── data_analysis.py # 數(shù)據(jù)分析工具
├── server.py           # 服務(wù)器入口
└── requirements.txt    # 依賴列表

核心代碼實(shí)現(xiàn)

# tools/stock_api.py
import httpx
from mcp.server.fastmcp import tool
from dotenv import load_dotenv
import os
 
load_dotenv()
 
@tool()
def get_stock_price(symbol: str) -> dict:
    """獲取股票實(shí)時(shí)價(jià)格(Alpha Vantage API)
    
    Args:
        symbol: 股票代碼(如"AAPL")
    
    Returns:
        包含價(jià)格、漲跌幅的字典
    """
    api_key = os.getenv('ALPHA_VANTAGE_KEY')
    url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={api_key}"
    
    response = httpx.get(url)
    data = response.json()
    
    if "Global Quote" not in data:
        return {"error": "未找到股票數(shù)據(jù)"}
    
    quote = data["Global Quote"]
    return {
        "symbol": symbol,
        "price": float(quote["05. price"]),
        "change": float(quote["09. change"]),
        "change_percent": float(quote["10. change percent"].strip('%'))
    }
 
# server.py
from fastmcp import FastMCP
from tools.stock_api import get_stock_price
from tools.data_analysis import calculate_stats
 
mcp = FastMCP("Stock Analysis Server")
mcp.add_tool(get_stock_price)
mcp.add_tool(calculate_stats)
 
if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="0.0.0.0", port=8000)

部署與測試

# 安裝依賴
uv install -r requirements.txt
 
# 啟動(dòng)服務(wù)器
python server.py
 
# 測試工具調(diào)用
curl -X POST http://localhost:8000/mcp/invoke \
  -H "Content-Type: application/json" \
  -d '{"toolName": "get_stock_price", "arguments": {"symbol": "AAPL"}}'

八、未來展望:MCP生態(tài)演進(jìn)方向

  • 工具市場:類似PyPI的MCP工具倉庫,實(shí)現(xiàn)"一鍵安裝"工具
  • 協(xié)議擴(kuò)展:支持gRPC、WebSocket等更多通信協(xié)議
  • 智能路由:根據(jù)請求內(nèi)容自動(dòng)選擇最優(yōu)工具
  • 邊緣計(jì)算:在IoT設(shè)備上部署輕量級MCP服務(wù)器

MCP協(xié)議正在重塑AI開發(fā)范式——它讓大模型從"封閉的大腦"進(jìn)化為"可連接萬物的神經(jīng)系統(tǒng)"。無論是個(gè)人開發(fā)者快速擴(kuò)展AI能力,還是企業(yè)整合遺留系統(tǒng),MCP都提供了標(biāo)準(zhǔn)化解決方案。當(dāng)工具調(diào)用變得像呼吸一樣自然,AI才能真正成為生產(chǎn)力的延伸。

以上就是基于Python從零構(gòu)建一個(gè)MCP服務(wù)器的詳細(xì)內(nèi)容,更多關(guān)于Python MCP服務(wù)器的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

大同市| 视频| 吉安县| 彭阳县| 临澧县| 津南区| 大城县| 临沂市| 乌兰县| 友谊县| 景德镇市| 六枝特区| 津南区| 仁布县| 泾川县| 藁城市| 庆城县| 尉犁县| 灵丘县| 剑川县| 高雄县| 兰坪| 昌黎县| 黎城县| 永德县| 额敏县| 罗城| 崇阳县| 平南县| 荣昌县| 衡南县| 即墨市| 临泽县| 城口县| 哈巴河县| 墨竹工卡县| 壶关县| 惠来县| 偃师市| 翼城县| 沂水县|