鸟类识别MCP服务器开发实战:让Cursor、Claude一键调用AI识别能力

举报
yd_218036793 发表于 2026/08/13 14:26:16 2026/08/13
【摘要】 本文旨在通过详细的步骤和易懂的讲解,实现一个能识别全球鸟类品种的MCP服务器的搭建和使用,跟着指南操作,你也能轻松理解MCP的概念及实战应用。

本文旨在通过详细的步骤和易懂的讲解,实现一个能识别全球鸟类品种的MCP服务器的搭建和使用,跟着指南操作,你也能轻松理解MCP的概念及实战应用。

文中集成的是快瞳鸟类品种识别API,快瞳的API接口采用标准的RESTful风格,通过获取AccessToken进行鉴权,然后调用具体的识别接口。快瞳全球鸟类品种识别API的核心能力包括:支持识别静止或飞行状态下的鸟类品种,已支持全球地区10000+鸟类品种识别,其中包括支持识别静止或飞行状态下的鸟类品种,已支持全球地区10000+鸟类品种识别,识别准确率95%以上,支持同时识别多只鸟并返回每个目标的置信度和坐标值。

以下是一个完整的MCP服务器实现示例:

集成快瞳鸟类品种识别API的MCP服务器

一、环境准备

# 创建项目目录
mkdir fastbird-mcp
cd fastbird-mcp
 
# 创建虚拟环境
python -m venv venv
# Windows用户
venv\Scripts\activate
# Mac/Linux用户
source venv/bin/activate
 
# 安装依赖
pip install mcp aiohttp anyio

二、创建服务器文件 server.py

import asyncio
import base64
import json
import os
from typing import Any
 
import aiohttp
from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationOptions
import mcp.server.stdio
import mcp.types as types
 
 
# ============ 配置区域 ============
# 从环境变量读取,也可以通过其他方式配置
FASTBIRD_API_KEY = os.environ.get("FASTBIRD_API_KEY", "your_api_key_here")
FASTBIRD_SECRET_KEY = os.environ.get("FASTBIRD_SECRET_KEY", "your_secret_key_here")
# 快瞳AI开放平台接口地址
BASE_URL = "https://ai.inspirvision.cn"
 
 
# ============ 快瞳API调用函数 ============
 
async def get_access_token() -> str:
    """
    获取快瞳API的AccessToken
    接口: POST /s/api/getAccessToken
    """
    async with aiohttp.ClientSession() as session:
        # 注意:实际接口参数需根据快瞳官方文档调整
        params = {
            "key": FASTBIRD_API_KEY,
            "secret": FASTBIRD_SECRET_KEY
        }
        async with session.post(
            f"{BASE_URL}/s/api/getAccessToken",
            params=params
        ) as resp:
            data = await resp.json()
            if data.get("code") == 0:
                return data.get("data", {}).get("accessToken")
            else:
                raise Exception(f"获取Token失败: {data}")
 
 
async def recognize_bird(image_base64: str) -> dict[str, Any]:
    """
    调用快瞳鸟类品种识别API
    接口: POST https://ai.inspirvision.cn/s/api/birdGlobalType
    支持识别静止或飞行状态下的鸟类品种
    """
    token = await get_access_token()
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "imgBase64": image_base64,
        # 可选参数: 是否返回坐标、识别阈值等
        "needLocation": True,
        "threshold": 0.5
    }
    
    async with aiohttp.ClientSession() as session:
        async with session.post(
            f"{BASE_URL}/s/api/bird/recognize",
            headers=headers,
            json=payload
        ) as resp:
            result = await resp.json()
            if result.get("code") == 0:
                return result.get("data", {})
            else:
                raise Exception(f"鸟类识别失败: {result}")
 
 
# ============ MCP服务器定义 ============
 
# 创建MCP Server实例
app = Server("fastbird-mcp")
 
 
@app.list_tools()
async def handle_list_tools() -> list[types.Tool]:
    """
    列出所有可用的工具
    当MCP客户端连接时,会调用此方法获取工具列表
    """
    return [
        types.Tool(
            name="recognize_bird",
            description=(
                "识别图片中的鸟类品种。"
                "支持全球地区10000+鸟类品种识别,国内1400+种,北美地1100+种,欧洲1000+种。"
                "支持识别静止或飞行状态下的鸟类。"
                "支持同时识别多只鸟,返回每个目标的品种名称、置信度和位置坐标。"
            ),
            inputSchema={
                "type": "object",
                "required": ["image"],
                "properties": {
                    "image": {
                        "type": "string",
                        "description": (
                            "图片数据,支持两种格式:"
                            "1. 图片的Base64编码字符串(不含data:image前缀)"
                            "2. 图片的URL地址"
                        ),
                    },
                    "image_type": {
                        "type": "string",
                        "enum": ["base64", "url"],
                        "description": "图片数据类型,默认为base64",
                        "default": "base64",
                    },
                    "threshold": {
                        "type": "number",
                        "description": "识别置信度阈值,范围0-1,默认0.5",
                        "minimum": 0,
                        "maximum": 1,
                        "default": 0.5,
                    },
                },
            },
        )
    ]
 
 
@app.call_tool()
async def handle_call_tool(
    name: str, 
    arguments: dict | None
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
    """
    处理工具调用请求
    当AI决定调用某个工具时,会通过此方法执行
    """
    if name != "recognize_bird":
        raise ValueError(f"未知工具: {name}")
    
    if not arguments:
        raise ValueError("缺少参数")
    
    image = arguments.get("image")
    if not image:
        raise ValueError("缺少image参数")
    
    image_type = arguments.get("image_type", "base64")
    threshold = arguments.get("threshold", 0.5)
    
    try:
        # 处理图片数据
        if image_type == "url":
            # 如果是URL,需要先下载图片再转Base64
            async with aiohttp.ClientSession() as session:
                async with session.get(image) as resp:
                    if resp.status != 200:
                        raise Exception(f"下载图片失败: HTTP {resp.status}")
                    img_data = await resp.read()
                    image_base64 = base64.b64encode(img_data).decode("utf-8")
        else:
            # 直接使用Base64数据
            image_base64 = image
        
        # 调用快瞳鸟类识别API
        result = await recognize_bird(image_base64)
        
        # 格式化返回结果
        birds = result.get("birds", [])
        if not birds:
            return [types.TextContent(
                type="text",
                text="未检测到鸟类。"
            )]
        
        # 构建可读的识别结果
        output_lines = ["🐦 鸟类识别结果:\n"]
        for i, bird in enumerate(birds, 1):
            name_cn = bird.get("name_cn", "未知")
            name_en = bird.get("name_en", "")
            confidence = bird.get("confidence", 0)
            location = bird.get("location", {})
            
            line = f"{i}. {name_cn}"
            if name_en:
                line += f" ({name_en})"
            line += f"\n   置信度: {confidence:.2%}"
            if location:
                line += f"\n   位置: x={location.get('x')}, y={location.get('y')}, "
                line += f"w={location.get('width')}, h={location.get('height')}"
            output_lines.append(line)
        
        output_lines.append(f"\n共识别到 {len(birds)} 只鸟类。")
        
        return [types.TextContent(
            type="text",
            text="\n".join(output_lines)
        )]
        
    except Exception as e:
        return [types.TextContent(
            type="text",
            text=f"识别失败: {str(e)}"
        )]
 
 
# ============ 启动服务器 ============
 
async def main():
    """
    启动MCP服务器
    使用stdio传输,与客户端通过标准输入输出通信
    """
    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
        await app.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="fastbird-mcp",
                server_version="1.0.0",
                capabilities=app.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                ),
            ),
        )
 
 
if __name__ == "__main__":
    asyncio.run(main())

三、配置文件 mcp.json(用于Claude Desktop等客户端)

如果要在Claude Desktop中使用这个MCP服务器,需要在配置文件中添加:

{
  "mcpServers": {
    "fastbird": {
      "command": "python",
      "args": ["/path/to/your/server.py"],
      "env": {
        "FASTBIRD_API_KEY": "your_api_key_here",
        "FASTBIRD_SECRET_KEY": "your_secret_key_here"
      }
    }
  }
}

四、运行与测试

# 确保在虚拟环境中
python server.py

服务器启动后,会通过stdio等待MCP客户端的连接。在支持MCP的AI 工具(如Cursor、Claude Desktop)中配置好后,你就可以用自然语言调用这个工具了:

用户:“帮我识别这张图片里是什么鸟”

AI会通过MCP协议自动调用recognize_bird工具,返回识别结果:

🐦 鸟类识别结果:
 
1. 白鹭 (Little Egret)
   置信度: 97.30%
   位置: x=120, y=85, w=180, h=220
 
共识别到 1 只鸟类。

五、核心要点说明

1. MCP Server的三大核心方法:

  • @app.list_tools():向客户端声明这个服务器提供了哪些工具
  • @app.call_tool():实际执行工具调用逻辑
  • main():通过stdio启动服务器,与客户端通信

2. 快瞳API调用流程:

  • 先通过key和secret获取AccessToken
  • 再用Token调用具体的鸟类识别接口
  • 识别结果包含品种名称(中英文)、置信度、位置坐标

3. MCP的价值:开发者只需实现一次这个MCP服务器,就可以在任意支持MCP的AI应用(Claude Desktop、Cursor、Cherry Studio等)中使用快瞳的鸟类识别能力,无需为每个应用重复开发集成代码。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。