跳转到主要内容
资源是由服务器公开的只读数据。资源可以是文件、生成的报告,或者服务器能够在不产生副作用的情况下提供的任何其他内容。
## 列出所有资源
from dedalus_mcp.client import open_connection

async with open_connection("http://127.0.0.1:8000/mcp") as client:
    resources = await client.list_resources()

    for r in resources.resources:
        print(f"{r.uri}: {r.name}")

资源模式

每个资源包含:
字段类型描述
uristr资源标识符(例如 resource://config/app
namestr人类可读名称
descriptionstr | None资源内容说明
mimeTypestr | None内容类型(例如 application/json
for r in resources.resources:
    print(f"URI: {r.uri}")
    print(f"Name: {r.name}")
    print(f"Type: {r.mimeType}")

读取资源

通过 URI 读取特定资源:
result = await client.read_resource("resource://config/app")
result 是一个带有 contents 列表的 ReadResourceResult。其中的元素可以是 TextResourceContents(文本)或 BlobResourceContents(base64 编码的二进制数据)。

响应结构(文本 vs 二进制)

import base64
from dedalus_mcp import types

result = await client.read_resource("resource://data/report")

if not result.contents:
    print("无内容(资源缺失或为空)")
else:
    item = result.contents[0]

    if isinstance(item, types.TextResourceContents):
        print(item.text)

    elif isinstance(item, types.BlobResourceContents):
        data = base64.b64decode(item.blob)  # blob 为 base64 编码文本
        with open("output.bin", "wb") as f:
            f.write(data)

示例:配置读取器

import json
from dedalus_mcp.client import open_connection
from dedalus_mcp import types

async with open_connection("http://127.0.0.1:8000/mcp") as client:
    resources = await client.list_resources()
    print("可用资源:")
    for r in resources.resources:
        print(f"  - {r.uri} ({r.mimeType})")

    result = await client.read_resource("resource://config/app")
    if not result.contents or not isinstance(result.contents[0], types.TextResourceContents):
        raise RuntimeError("Expected text config resource")

    data = json.loads(result.contents[0].text)
    print(f"应用配置:{data}")

资源模板

资源模板只是服务器可以发布的“模式”(比如 resource://users/),用于展示有哪些类型的资源 URL。它们不会自动创建资源——要读取某个资源,你仍然需要使用真实的 URL(比如 resource://users/123)调用 read_resource(…),并且只有在服务器实际提供该精确 URI 时才会生效。
## 上下文管理器
同样,open_connection(...) 是一个异步上下文管理器。这意味着你不必手动调用 await client.close()。当 async with 代码块结束时,它会自动为你关闭底层连接。
from dedalus_mcp.client import open_connection

async with open_connection("http://127.0.0.1:8000/mcp") as client:
    resources = await client.list_resources()
    result = await client.read_resource("resource://docs/readme")
Last modified on April 11, 2026