diff --git a/CLAUDE.md b/CLAUDE.md index da3cea7..404227d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,9 +8,23 @@ MCP server providing Example API functionality via FastMCP. src/mcp_example/ ├── server.py # MCP tools (FastMCP) + entrypoints ├── api_client.py # Async HTTP client for Example API -└── api_models.py # Pydantic models for API responses +├── api_models.py # Pydantic models for API responses +└── skills/ + └── example/ + └── SKILL.md # The skill served at skill://example/SKILL.md ``` +## Server SDK + +The server is built on `nimblebrain-server-sdk` ([quickstart](https://docs.nimblebrain.ai/server-sdk/quickstart/)). +Use it instead of writing these by hand: + +- **Annotations**: every tool carries `READS`, `ADDS` or `CHANGES` (`@mcp.tool(annotations=READS)`). A tool with none reads to a client as a destructive write. +- **Errors**: a tool returns a failure with `to_tool_error(ServiceError(ErrorCode.X, "..."))` from `nimblebrain_server_sdk.errors`. Never return a dict that describes an error, and never raise `ValueError` for a caller's mistake. Classify an API failure with `ServiceError.from_upstream(status, detail=...)`; the API's own text goes in `detail` (logged), never in the message. ([Errors](https://docs.nimblebrain.ai/server-sdk/errors/)) +- **Skills**: a skill is a directory under `skills/` whose name equals the `name` in its `SKILL.md` frontmatter, registered in the one `add_skills(mcp, [...])` call. Do not serve a `skill://` resource by hand. ([Skills](https://docs.nimblebrain.ai/server-sdk/skills/)) +- **Listings**: a listing tool builds each row with `listing_row`, with a `uri` and a preview in place of any unbounded text field. The `uri` must resolve: a resource template (`example://items/{item_id}`) returns the whole record. +- **Tests**: run each test that crosses the wire on both protocol versions (`Client(mcp, mode="auto")` and `mode="legacy"`), check skills with `served_skills` and listing rows with `assert_bounded_rows`. ([Testing](https://docs.nimblebrain.ai/server-sdk/testing/)) + ## Critical - Package name: `@nimblebraininc/example` (npm-style scope, matches GitHub org) @@ -22,7 +36,7 @@ src/mcp_example/ mcp.run() # Stdio for Claude Desktop / mpak ``` - All logs to stderr (stdout is reserved for JSON-RPC) -- A failure the caller must see is a raised `ToolError`; never log to the client with `ctx.info`/`ctx.error` (MCP's logging capability is deprecated as of 2026-07-28, SEP-2577) +- A failure the caller must see is returned with `to_tool_error`; never log to the client with `ctx.info`/`ctx.error` (MCP's logging capability is deprecated as of 2026-07-28, SEP-2577) ## user_config @@ -90,6 +104,7 @@ GitHub Actions builds and uploads MCPB bundles automatically on release. 1. Add response model to `api_models.py` 2. Add client method to `api_client.py` -3. Add `@mcp.tool()` function to `server.py` -4. Add tests to `tests/` -5. Run `make check` to verify +3. Add `@mcp.tool(annotations=...)` function to `server.py` +4. Add a row for the tool to `skills/example/SKILL.md` +5. Add tests to `tests/` +6. Run `make check` to verify diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77d3a7c..71ff51c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,15 +39,17 @@ npx skills add nimblebraininc/skills --skill mcpb --agent claude-code -y 1. **Add response models** to `src/mcp_example/api_models.py` 2. **Add client methods** to `src/mcp_example/api_client.py` -3. **Add the tool** to `src/mcp_example/server.py` using `@mcp.tool()` -4. **Add tests** to `tests/` -5. **Run checks**: `make check` +3. **Add the tool** to `src/mcp_example/server.py` using `@mcp.tool(annotations=...)` +4. **Describe the tool** in `src/mcp_example/skills/example/SKILL.md` +5. **Add tests** to `tests/`, run on both protocol versions +6. **Run checks**: `make check` ### Tool Design Guidelines - One tool per API operation (`list_items`, `get_item`, `create_item`) - Clear docstrings with Args/Returns sections -- Report a failure the caller must see by raising `ToolError` (from `fastmcp.exceptions`) with a message safe to show, and log diagnostics to stderr with the `logging` module. Do not send logs to the client (`ctx.info`, `ctx.error`): MCP's logging capability is deprecated as of the 2026-07-28 protocol (SEP-2577) +- Annotate every tool with `READS`, `ADDS` or `CHANGES` from `nimblebrain_server_sdk` +- Report a failure the caller must see by returning `to_tool_error(ServiceError(ErrorCode.X, "..."))` (from `nimblebrain_server_sdk.errors`) with a message safe to show, and log diagnostics to stderr with the `logging` module. See the [errors guide](https://docs.nimblebrain.ai/server-sdk/errors/). Do not send logs to the client (`ctx.info`, `ctx.error`): MCP's logging capability is deprecated as of the 2026-07-28 protocol (SEP-2577) - Return Pydantic models, not raw dicts ### Code Quality @@ -89,6 +91,6 @@ Or simply: `make check` - MTF scanner passes (no critical/high findings) ### For Companion Skills -- SKILL.md with complete frontmatter +- A directory under `src/mcp_example/skills/` named after the skill, holding a `SKILL.md` whose frontmatter has that `name` and a `description`, registered with `add_skills` - Composes 2+ tools into a workflow - At least 2 usage examples diff --git a/README.md b/README.md index 5c6e056..af5c0c2 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ An MCP (Model Context Protocol) server that provides access to the Example API, - List and retrieve items from the Example API - Async HTTP client with error handling - Typed responses with Pydantic models +- Built on the [NimbleBrain server SDK](#built-on-the-nimblebrain-server-sdk): annotated tools, classified errors, and a skill served to the host ## Installation @@ -64,8 +65,100 @@ Add to your `~/.claude/settings.json`: | Tool | Description | |------|-------------| -| `list_items` | List items from the API with optional limit | -| `get_item` | Get a single item by its ID | +| `list_items` | List items from the API with optional limit. Each row carries a `uri` and a preview of the description | +| `get_item` | Get a single item, whole, by its ID | + +Both tools read and change nothing, and say so with the `READS` annotation. A row's `uri` +(`example://items/`) is a resource that returns the whole item as JSON. The server also +serves one skill, `skill://example/SKILL.md`, which tells an agent when to use each tool. + +## Built on the NimbleBrain server SDK + +The server uses [`nimblebrain-server-sdk`](https://pypi.org/project/nimblebrain-server-sdk/) +for what every server on NimbleBrain shares. Start with the +[quickstart](https://docs.nimblebrain.ai/server-sdk/quickstart/). + +| The server does this | With | Guide | +|---|---|---| +| Declares what each tool can change | `READS`, `ADDS`, `CHANGES` | [Quickstart](https://docs.nimblebrain.ai/server-sdk/quickstart/) | +| Returns a failure with a code the caller can act on | `to_tool_error`, `ServiceError`, `ErrorCode` | [Errors](https://docs.nimblebrain.ai/server-sdk/errors/) | +| Serves the skill in `src/mcp_example/skills/` | `add_skills` | [Skills](https://docs.nimblebrain.ai/server-sdk/skills/) | +| Tests what a host sees, on both protocol versions | `served_skills`, `assert_bounded_rows` | [Testing](https://docs.nimblebrain.ai/server-sdk/testing/) | + +### A tool + +A tool carries one annotation: `READS`, `ADDS` (a write that loses nothing) or `CHANGES` (a +write that overwrites or removes). It returns a failure with `to_tool_error`; it does not +return a dict that describes the error, and it does not raise for a caller's mistake. + +```python +from fastmcp import FastMCP +from nimblebrain_server_sdk import ADDS +from nimblebrain_server_sdk.errors import ErrorCode, ServiceError, to_tool_error + +mcp = FastMCP("Example") + +ITEMS: dict[str, str] = {} + + +@mcp.tool(annotations=ADDS) +async def create_item(name: str) -> dict[str, str]: + """Create an item and return it.""" + if not name.strip(): + return to_tool_error(ServiceError(ErrorCode.BAD_INPUT, "`name` is empty.")) + item_id = str(len(ITEMS) + 1) + ITEMS[item_id] = name + return {"id": item_id, "name": name} +``` + +The caller of `create_item` with an empty name receives an error result whose structured +content is `{"error": {"code": "bad_input", "retryable": false, "message": "`name` is empty."}}`. + +### A skill + +A skill is a directory that holds a `SKILL.md`. The frontmatter needs a `name` and a +`description`, and `name` must equal the directory's name. `add_skills` checks every skill +when the server is imported and serves each at `skill:///SKILL.md`: + +```python +from pathlib import Path + +from fastmcp import FastMCP +from nimblebrain_server_sdk import add_skills + +mcp = FastMCP("Example") +add_skills(mcp, [Path("src/mcp_example/skills/example")]) +``` + +### A test + +A host connects on one of two protocol versions, so a test runs on both: +`Client(mcp, mode="auto")` negotiates 2026-07-28 and `mode="legacy"` runs the 2025-11-25 +handshake. `served_skills` reads every skill file back the way a host does. + +```python +import pytest +from fastmcp import Client +from nimblebrain_server_sdk.testing import served_skills + +from mcp_example.server import mcp + + +@pytest.mark.parametrize("mode", ["auto", "legacy"]) +async def test_the_skill_is_served(mode): + skills = await served_skills(mcp, mode) + assert set(skills) == {"skill://example/SKILL.md"} + + +@pytest.mark.parametrize("mode", ["auto", "legacy"]) +async def test_an_empty_item_id_is_bad_input(mode): + async with Client(mcp, mode=mode) as client: + result = await client.call_tool("get_item", {"item_id": " "}, raise_on_error=False) + assert result.is_error + assert result.structured_content["error"]["code"] == "bad_input" +``` + +`tests/test_server.py` holds the full set. ## Development diff --git a/pyproject.toml b/pyproject.toml index 90c93b1..7fc3699 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,7 @@ classifiers = [ dependencies = [ "aiohttp>=3.11.0", "fastmcp>=4.0.0", + "nimblebrain-server-sdk>=0.6.1", "pydantic>=2.0.0", "python-dotenv>=1.0.0", ] diff --git a/src/mcp_example/SKILL.md b/src/mcp_example/SKILL.md deleted file mode 100644 index eb3760c..0000000 --- a/src/mcp_example/SKILL.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -name: mcp-example-service -description: Provides knowledge of how to use MCP example most effectively. It's loaded into the agent's context when running the MCP. ---- - -## Tools - - -| Tool | Use when... | -|------|-------------| - -## Context Reuse - - - -## Workflows - - diff --git a/src/mcp_example/server.py b/src/mcp_example/server.py index 39cee33..7c3a782 100644 --- a/src/mcp_example/server.py +++ b/src/mcp_example/server.py @@ -8,16 +8,24 @@ 2. Update manifest.json, server.json, pyproject.toml with your service info 3. Implement your API client in api_client.py 4. Add Pydantic models in api_models.py -5. Add tools below using @mcp.tool() +5. Add tools below using @mcp.tool(annotations=...) +6. Describe them in skills/example/SKILL.md (rename the directory and its `name` together) + +The server is built on nimblebrain-server-sdk: tool annotations, the error contract and +skills come from it. Guide: https://docs.nimblebrain.ai/server-sdk/quickstart/ """ +import json import logging import os import sys -from importlib.resources import files +from pathlib import Path +from typing import Any from fastmcp import FastMCP -from fastmcp.exceptions import ToolError +from fastmcp.exceptions import ResourceError +from nimblebrain_server_sdk import PREVIEW_CHARS, READS, add_skills, listing_row +from nimblebrain_server_sdk.errors import ErrorCode, ServiceError, to_tool_error from starlette.requests import Request from starlette.responses import JSONResponse @@ -25,7 +33,7 @@ # Logging setup - all logs to stderr (stdout is reserved for JSON-RPC). Diagnostics go # here, never to the client: MCP's logging capability is deprecated as of the 2026-07-28 -# protocol (SEP-2577). A failure the caller must see is raised as a ToolError. +# protocol (SEP-2577). A failure the caller must see is returned with to_tool_error. logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", @@ -35,16 +43,21 @@ logger.info("Example server module loading...") -SKILL_CONTENT = files("mcp_example").joinpath("SKILL.md").read_text() +# Each skill is a directory holding a SKILL.md whose frontmatter `name` equals the +# directory's name. A skill is served at skill:///SKILL.md. +SKILLS_DIR = Path(__file__).parent / "skills" + +MAX_LIMIT = 100 # Create MCP server mcp = FastMCP( "Example", instructions=( - "Before using tools, read the skill://example/usage resource " + "Before using tools, read the skill://example/SKILL.md resource " "for tool selection guidance and workflow patterns." ), ) +add_skills(mcp, [SKILLS_DIR / "example"]) # Global client instance (lazy initialization) _client: ExampleClient | None = None @@ -54,18 +67,29 @@ async def get_client() -> ExampleClient: """Get or create the API client instance. Raises: - ToolError: when EXAMPLE_API_KEY is not set, so the caller sees why the tool failed. + ServiceError: when EXAMPLE_API_KEY is not set, so the caller sees why the tool failed. """ global _client if _client is None: api_key = os.environ.get("EXAMPLE_API_KEY") if not api_key: - logger.error("EXAMPLE_API_KEY is not set") - raise ToolError("EXAMPLE_API_KEY environment variable is required") + raise ServiceError( + ErrorCode.AUTH_REQUIRED, + "EXAMPLE_API_KEY environment variable is required", + ) _client = ExampleClient(api_key=api_key) return _client +def upstream_error(error: ExampleAPIError) -> ServiceError: + """Classify an Example API failure by its HTTP status. + + The caller receives the code, the status and a generic message. The API's own text + may name internals, so it goes to `detail`, which is logged and never returned. + """ + return ServiceError.from_upstream(error.status, detail=error.message) + + # Health endpoint for HTTP transport @mcp.custom_route("/health", methods=["GET"]) async def health_check(request: Request) -> JSONResponse: @@ -75,33 +99,69 @@ async def health_check(request: Request) -> JSONResponse: # ============================================================================ # Tools - Add your MCP tools below +# +# Every tool declares what a call can change: READS, ADDS (a write that loses +# nothing) or CHANGES (a write that overwrites or removes). A tool with no +# annotation reads to a client as a destructive write. +# +# A failure is returned, never raised: `return to_tool_error(ServiceError(...))`. # ============================================================================ -@mcp.tool() +@mcp.tool(annotations=READS) async def list_items( limit: int = 20, -) -> list[dict]: +) -> list[dict[str, Any]]: """List items from the Example API. Args: limit: Maximum number of items to return (1-100, default 20) Returns: - List of items + One row per item. A row carries the item's `uri` and a `description_preview` + in place of the full description. `get_item`, or a read of the `uri`, returns + the whole item. """ - client = await get_client() + if not 1 <= limit <= MAX_LIMIT: + return to_tool_error( + ServiceError(ErrorCode.BAD_INPUT, f"`limit` must be between 1 and {MAX_LIMIT}.") + ) try: - return await client.list_items(limit=limit) + client = await get_client() + items = await client.list_items(limit=limit) + except ServiceError as e: + return to_tool_error(e) except ExampleAPIError as e: - logger.warning("list_items failed: %s", e) - raise ToolError(str(e)) from e + return to_tool_error(upstream_error(e)) + # A page holds many rows, so an unbounded field leaves each row as a preview. + return [ + listing_row( + {**item, "uri": f"example://items/{item['id']}"}, + preview={"description": PREVIEW_CHARS}, + ) + for item in items + ] + +async def read_item(item_id: str) -> dict[str, Any]: + """Read one whole item, for the tool and the resource that both return it. -@mcp.tool() + Raises: + ServiceError: classified, with a message safe to show the caller. + """ + if not item_id.strip(): + raise ServiceError(ErrorCode.BAD_INPUT, "`item_id` is empty.") + try: + client = await get_client() + return await client.get_item(item_id) + except ExampleAPIError as e: + raise upstream_error(e) from e + + +@mcp.tool(annotations=READS) async def get_item( item_id: str, -) -> dict: +) -> dict[str, Any]: """Get a single item by ID. Args: @@ -110,12 +170,10 @@ async def get_item( Returns: Item details """ - client = await get_client() try: - return await client.get_item(item_id) - except ExampleAPIError as e: - logger.warning("get_item failed: %s", e) - raise ToolError(str(e)) from e + return await read_item(item_id) + except ServiceError as e: + return to_tool_error(e) # ============================================================================ @@ -123,10 +181,17 @@ async def get_item( # ============================================================================ -@mcp.resource("skill://example/usage") -def skill_usage() -> str: - """Usage guide for the Example MCP server tools.""" - return SKILL_CONTENT +# The address a `list_items` row carries in `uri`. A row is a summary, so its uri must +# read back the whole record. +@mcp.resource("example://items/{item_id}", name="item", mime_type="application/json") +async def item_resource(item_id: str) -> str: + """One whole item, as JSON: the same record `get_item` returns.""" + try: + return json.dumps(await read_item(item_id)) + except ServiceError as e: + # A resource read has no tool result to carry the error envelope, so the failure + # is the read's error, with the same message safe to show. + raise ResourceError(e.message) from e # ============================================================================ diff --git a/src/mcp_example/skills/example/SKILL.md b/src/mcp_example/skills/example/SKILL.md new file mode 100644 index 0000000..fb46f1b --- /dev/null +++ b/src/mcp_example/skills/example/SKILL.md @@ -0,0 +1,29 @@ +--- +name: example +description: How to find and read items with the Example server's tools. Use when a request names an item, or asks what items exist. +--- + +## Tools + +| Tool | Use when... | +|------|-------------| +| `list_items` | The request does not name an item id: browse or find items. Each row is a summary with the item's `id` and `uri`. | +| `get_item` | You hold an item id and need the whole item, including its full description. | + +## Context Reuse + +- `list_items` rows carry `id`. Pass it to `get_item` as `item_id`. +- A row's `description_preview` is cut short. Call `get_item`, or read the row's `uri`, before quoting or summarizing a description. + +## Workflows + +### Find an item and read it + +1. `list_items` (raise `limit`, up to 100, when the item is not on the first page). +2. Pick the row whose `name` matches the request. +3. `get_item` with that row's `id`. + +### Handle a failure + +A failed call returns an error with a `code`. On `not_found`, list again and pick an id from the +rows. On `bad_input`, fix the argument the message names. Retry only when `retryable` is true. diff --git a/tests/conftest.py b/tests/conftest.py index feb2172..7d7de10 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,6 +6,9 @@ from mcp_example.server import mcp +# Longer than any listing row may carry, so a row that leaks it fails assert_bounded_rows. +LONG_DESCRIPTION = "A long description. " * 100 + @pytest.fixture def mcp_server(): @@ -19,15 +22,15 @@ def mock_client(): client = AsyncMock() client.list_items = AsyncMock( return_value=[ - {"id": "1", "name": "Item 1"}, - {"id": "2", "name": "Item 2"}, + {"id": "1", "name": "Item 1", "description": LONG_DESCRIPTION}, + {"id": "2", "name": "Item 2", "description": LONG_DESCRIPTION}, ] ) client.get_item = AsyncMock( return_value={ "id": "1", "name": "Item 1", - "description": "Test item", + "description": LONG_DESCRIPTION, } ) return client diff --git a/tests/test_server.py b/tests/test_server.py index 504d62c..63ef5ee 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1,110 +1,184 @@ -"""Tests for Example MCP Server tools and skill resource.""" +"""Tests for the Example MCP server: its skill, its tools and its errors. +A host may connect on either protocol era, so every test that crosses the wire runs on +both: `"auto"` negotiates 2026-07-28 and `"legacy"` runs the 2025-11-25 handshake. +""" + +import json from unittest.mock import patch import pytest from fastmcp import Client -from fastmcp.exceptions import ToolError +from mcp.shared.exceptions import MCPError +from nimblebrain_server_sdk.testing import assert_bounded_rows, served_skills from mcp_example.api_client import ExampleAPIError -from mcp_example.server import SKILL_CONTENT +from mcp_example.server import SKILLS_DIR +from tests.conftest import LONG_DESCRIPTION + +MODES = ["auto", "legacy"] # 2026-07-28, then 2025-11-25 +SKILL_URI = "skill://example/SKILL.md" + +@pytest.mark.parametrize("mode", MODES) +class TestSkill: + """The skill a host reads before it uses the tools.""" -class TestSkillResource: - """Test the skill resource and server instructions.""" + async def test_skill_is_served(self, mcp_server, mode): + """served_skills reads every skill file back and checks it against its listing.""" + skills = await served_skills(mcp_server, mode) + assert set(skills) == {SKILL_URI} + frontmatter = skills[SKILL_URI]["frontmatter"] + assert frontmatter["name"] == "example" + assert frontmatter["description"] - @pytest.mark.asyncio - async def test_initialize_returns_instructions(self, mcp_server): - """Server instructions reference the skill resource.""" - async with Client(mcp_server) as client: - # client.instructions reads whichever negotiation result the protocol era - # produced; client.initialize() raises on the modern (server/discover) era. + async def test_instructions_name_the_skill(self, mcp_server, mode): + """Server instructions point at a resource the server serves.""" + async with Client(mcp_server, mode=mode) as client: assert client.instructions is not None - assert "skill://example/usage" in client.instructions - - @pytest.mark.asyncio - async def test_skill_resource_listed(self, mcp_server): - """skill://example/usage appears in resource listing.""" - async with Client(mcp_server) as client: - resources = await client.list_resources() - uris = [str(r.uri) for r in resources] - assert "skill://example/usage" in uris - - @pytest.mark.asyncio - async def test_skill_resource_readable(self, mcp_server): - """Reading the skill resource returns the full skill content.""" - async with Client(mcp_server) as client: - contents = await client.read_resource("skill://example/usage") - text = contents[0].text if hasattr(contents[0], "text") else str(contents[0]) - assert len(text.strip()) > 0 - assert "## Tools" in text - - @pytest.mark.asyncio - async def test_skill_content_matches_constant(self, mcp_server): - """Resource content matches the SKILL_CONTENT constant.""" - async with Client(mcp_server) as client: - contents = await client.read_resource("skill://example/usage") - text = contents[0].text if hasattr(contents[0], "text") else str(contents[0]) - assert text == SKILL_CONTENT + assert SKILL_URI in client.instructions + (content,) = await client.read_resource(SKILL_URI) + assert content.text == (SKILLS_DIR / "example" / "SKILL.md").read_text() + + async def test_skill_names_every_tool(self, mcp_server, mode): + """The skill covers each tool the server lists.""" + async with Client(mcp_server, mode=mode) as client: + tools = await client.list_tools() + skill = (SKILLS_DIR / "example" / "SKILL.md").read_text() + for tool in tools: + assert f"`{tool.name}`" in skill +@pytest.mark.parametrize("mode", MODES) class TestToolListing: - """Test that all tools are registered and discoverable.""" + """What a host learns about the tools before it calls one.""" - @pytest.mark.asyncio - async def test_all_tools_listed(self, mcp_server): + async def test_all_tools_listed(self, mcp_server, mode): """All expected tools appear in tool listing.""" - async with Client(mcp_server) as client: + async with Client(mcp_server, mode=mode) as client: + tools = await client.list_tools() + assert {t.name for t in tools} == {"list_items", "get_item"} + + async def test_every_tool_is_annotated(self, mcp_server, mode): + """A tool with no annotation reads to a client as a destructive write.""" + async with Client(mcp_server, mode=mode) as client: tools = await client.list_tools() - names = {t.name for t in tools} - expected = {"list_items", "get_item"} - assert expected == names + for tool in tools: + assert tool.annotations is not None, tool.name + assert tool.annotations.read_only_hint is not None, tool.name -class TestMCPTools: - """Test the MCP server tools via FastMCP Client.""" +@pytest.mark.parametrize("mode", MODES) +class TestTools: + """The tools, called the way a host calls them.""" - @pytest.mark.asyncio - async def test_list_items(self, mcp_server, mock_client): - """Test list_items tool.""" + async def test_list_items_returns_bounded_rows(self, mcp_server, mock_client, mode): + """A listing row carries its address and a preview, never the whole description.""" with patch("mcp_example.server.get_client", return_value=mock_client): - async with Client(mcp_server) as client: + async with Client(mcp_server, mode=mode) as client: result = await client.call_tool("list_items", {"limit": 10}) - assert result is not None - mock_client.list_items.assert_called_once_with(limit=10) - - @pytest.mark.asyncio - async def test_get_item(self, mcp_server, mock_client): - """Test get_item tool.""" + mock_client.list_items.assert_called_once_with(limit=10) + rows = result.data + assert_bounded_rows(rows, unbounded=["description"]) + assert [row["uri"] for row in rows] == ["example://items/1", "example://items/2"] + assert LONG_DESCRIPTION.startswith(rows[0]["description_preview"].rstrip("…")) + + async def test_get_item_returns_the_whole_item(self, mcp_server, mock_client, mode): + """get_item returns the fields a listing row cuts short.""" with patch("mcp_example.server.get_client", return_value=mock_client): - async with Client(mcp_server) as client: + async with Client(mcp_server, mode=mode) as client: result = await client.call_tool("get_item", {"item_id": "1"}) - assert result is not None - mock_client.get_item.assert_called_once_with("1") + mock_client.get_item.assert_called_once_with("1") + assert result.data == {"id": "1", "name": "Item 1", "description": LONG_DESCRIPTION} + - @pytest.mark.asyncio - async def test_list_items_api_error(self, mcp_server, mock_client): - """Test list_items handles API errors.""" - mock_client.list_items.side_effect = ExampleAPIError(401, "Unauthorized") +@pytest.mark.parametrize("mode", MODES) +class TestItemResource: + """The address a listing row carries reads back the whole record.""" + + async def test_a_row_uri_reads_the_whole_item(self, mcp_server, mock_client, mode): + """Reading the uri from a list_items row returns what get_item returns.""" + with patch("mcp_example.server.get_client", return_value=mock_client): + async with Client(mcp_server, mode=mode) as client: + rows = (await client.call_tool("list_items", {})).data + (content,) = await client.read_resource(rows[0]["uri"]) + item = (await client.call_tool("get_item", {"item_id": rows[0]["id"]})).data + assert content.mime_type == "application/json" + assert json.loads(content.text) == item + assert item["description"] == LONG_DESCRIPTION + + async def test_the_item_address_is_listed(self, mcp_server, mode): + """A host finds the address shape in the resource templates.""" + async with Client(mcp_server, mode=mode) as client: + templates = await client.list_resource_templates() + assert [t.uri_template for t in templates] == ["example://items/{item_id}"] + + async def test_a_missing_item_fails_the_read(self, mcp_server, mock_client, mode): + """A failed read carries the classified message, not the API's own text.""" + mock_client.get_item.side_effect = ExampleAPIError(404, "no row in items_v2") + with patch("mcp_example.server.get_client", return_value=mock_client): + async with Client(mcp_server, mode=mode) as client: + with pytest.raises(MCPError) as failure: + await client.read_resource("example://items/missing") + assert "The requested resource was not found." in str(failure.value) + assert "items_v2" not in str(failure.value) + + +async def call_for_error(mcp_server, mode, tool, arguments): + """Call a tool that must fail, and return the error a host receives.""" + async with Client(mcp_server, mode=mode) as client: + result = await client.call_tool(tool, arguments, raise_on_error=False) + assert result.is_error + return result.structured_content["error"] + + +@pytest.mark.parametrize("mode", MODES) +class TestErrors: + """A failure reaches the caller as an error with a code it can act on.""" + + @pytest.mark.parametrize( + ("tool", "arguments", "message"), + [ + ("list_items", {"limit": 0}, "`limit` must be between 1 and 100."), + ("list_items", {"limit": 101}, "`limit` must be between 1 and 100."), + ("get_item", {"item_id": " "}, "`item_id` is empty."), + ], + ) + async def test_a_caller_mistake_is_bad_input(self, mcp_server, mode, tool, arguments, message): + """A bad argument is refused before the API is called.""" + with patch("mcp_example.server.get_client") as get_client: + error = await call_for_error(mcp_server, mode, tool, arguments) + get_client.assert_not_called() + assert error == {"code": "bad_input", "retryable": False, "message": message} + + async def test_a_missing_item_is_not_found(self, mcp_server, mock_client, mode): + """An API 404 is classified, and the API's own text stays out of the result.""" + mock_client.get_item.side_effect = ExampleAPIError(404, "no row in items_v2") with patch("mcp_example.server.get_client", return_value=mock_client): - async with Client(mcp_server) as client: - with pytest.raises(ToolError, match="401"): - await client.call_tool("list_items", {}) - - @pytest.mark.asyncio - async def test_get_item_api_error(self, mcp_server, mock_client): - """An API failure reaches the caller as a tool error carrying the status.""" - mock_client.get_item.side_effect = ExampleAPIError(404, "Not found") + error = await call_for_error(mcp_server, mode, "get_item", {"item_id": "missing"}) + assert error == { + "code": "not_found", + "retryable": False, + "message": "The requested resource was not found.", + "upstream_status": 404, + } + + async def test_a_rate_limit_is_retryable(self, mcp_server, mock_client, mode): + """An API 429 tells the caller a retry can help.""" + mock_client.list_items.side_effect = ExampleAPIError(429, "Rate limit exceeded") with patch("mcp_example.server.get_client", return_value=mock_client): - async with Client(mcp_server) as client: - with pytest.raises(ToolError, match="404"): - await client.call_tool("get_item", {"item_id": "missing"}) + error = await call_for_error(mcp_server, mode, "list_items", {}) + assert error["code"] == "rate_limited" + assert error["retryable"] is True + assert error["upstream_status"] == 429 - @pytest.mark.asyncio - async def test_missing_api_key_is_a_tool_error(self, mcp_server, monkeypatch): + async def test_a_missing_api_key_is_auth_required(self, mcp_server, monkeypatch, mode): """Without EXAMPLE_API_KEY the caller sees why the tool failed.""" monkeypatch.delenv("EXAMPLE_API_KEY", raising=False) monkeypatch.setattr("mcp_example.server._client", None) - async with Client(mcp_server) as client: - with pytest.raises(ToolError, match="EXAMPLE_API_KEY"): - await client.call_tool("list_items", {}) + error = await call_for_error(mcp_server, mode, "list_items", {}) + assert error == { + "code": "auth_required", + "retryable": False, + "message": "EXAMPLE_API_KEY environment variable is required", + }