MCP 服务器中的资源

Model Context Protocol (MCP) 入门

James Chapman

AI Curriculum Manager, DataCamp

什么是 MCP 资源?

 

第 2 章

  • 资源 + 提示

原语1

Model Context Protocol (MCP) 入门

什么是 MCP 资源?

 

第 2 章

  • 资源与提示
  • 与 API 和数据库集成

资源:由 MCP 客户端获取的只读数据或数据对象

  • 不一定由 LLM 调用
  • 应用驱动 → 如用户偏好
  • 用户驱动 → 如文件上传

原语2

Model Context Protocol (MCP) 入门

AI 应用中的 MCP 资源

 

MCP 资源

Model Context Protocol (MCP) 入门

定义 MCP 服务器资源

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")


@mcp.resource("file://locations.txt")
def get_locations(): try: with open('locations.txt', 'r') as f: content = f.read() return content except FileNotFoundError: return "locations.txt file not found"

 

  • URI:统一资源标识符

    • 可指向本地文件、API、远程服务器等
    • 可动态插入参数,如用户 ID
  • locations.txt(服务器端)→ 时区位置列表

Model Context Protocol (MCP) 入门

定义 MCP 服务器资源

@mcp.resource("file://locations.txt")
def get_locations() -> str:
    """
    Get the list of cities for timezone conversion.

    Returns:
        Contents of the locations.txt file with city names
    """
    try:
        with open('locations.txt', 'r') as f:
            content = f.read()
        return content
    except FileNotFoundError:
        return "locations.txt file not found"
Model Context Protocol (MCP) 入门

保存服务器:timezone_server.py

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")

# Tools from before...

@mcp.resource("file://locations.txt")
def get_locations() -> str:
    # ...

if __name__ == "__main__":
    mcp.run(transport="stdio")
Model Context Protocol (MCP) 入门

客户端:列出资源

async def list_resources():
    """List all available resources from the MCP server."""
    params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

response = await session.list_resources()
print("Available resources:") for resource in response.resources: print(f" - {resource.uri}") print(f" Name: {resource.name}") print(f" Description: {resource.description}") return response.resources
Model Context Protocol (MCP) 入门

客户端:列出资源

print(asyncio.run(list_resources()))
Available resources:
 - file://locations.txt/
   Name: get_locations
   Description: 
    Get the list of cities for timezone conversion.

    Returns:
        Contents of the locations.txt file with city names

[Resource(name='get_locations', title=None, uri=AnyUrl('file://locations.txt/'),
          description='\n    Get the list of cities for timezone conversion.\n\n...',
          mimeType='text/plain', size=None, icons=None, annotations=None, meta=None)]
Model Context Protocol (MCP) 入门

客户端:读取资源

async def read_resource(resource_uri: str):
    """Read a specific resource by URI."""
    params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

print(f"Reading resource: {resource_uri}") resource_content = await session.read_resource(resource_uri)
for content in resource_content.contents: print(f"\nContent ({content.mimeType}):") print(content.text) return resource_content
Model Context Protocol (MCP) 入门

客户端:读取资源

print(asyncio.run(read_resource('file://locations.txt/')))
Reading resource: file://locations.txt

Content (text/plain):
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
...

ReadResourceResult(meta=None, contents=[TextResourceContents(uri=AnyUrl('file://locations.txt/'),
                   mimeType='text/plain', meta=None, text='Africa/Abidjan\nAfrica/Accra...')])
Model Context Protocol (MCP) 入门

Vamos praticar!

Model Context Protocol (MCP) 入门

Preparing Video For Download...