diff --git a/CLAUDE.md b/CLAUDE.md index 404227d..9a983dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,10 +20,10 @@ The server is built on `nimblebrain-server-sdk` ([quickstart](https://docs.nimbl 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/)) +- **Errors**: a tool reports a failure by raising `ServiceError(ErrorCode.X, "...")` from `nimblebrain_server_sdk.errors`. `add_error_contract(mcp)`, called once where the server is built, returns it to the caller as an error result with its code. Never return a dict that describes an error (a host and a model score it as a success), 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/)) +- **Tests**: run each test that crosses the wire on both protocol versions (`Client(mcp, mode="auto")` and `mode="legacy"`), annotate the parametrized `mode` with `Mode` from `nimblebrain_server_sdk.testing`, check skills with `served_skills` and listing rows with `assert_bounded_rows`. ([Testing](https://docs.nimblebrain.ai/server-sdk/testing/)) ## Critical @@ -36,7 +36,7 @@ Use it instead of writing these by hand: mcp.run() # Stdio for Claude Desktop / mpak ``` - All logs to stderr (stdout is reserved for JSON-RPC) -- 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) +- A failure the caller must see is a raised `ServiceError`; 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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 71ff51c..76a4e86 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,7 +49,7 @@ npx skills add nimblebraininc/skills --skill mcpb --agent claude-code -y - One tool per API operation (`list_items`, `get_item`, `create_item`) - Clear docstrings with Args/Returns sections - 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) +- Report a failure the caller must see by raising `ServiceError(ErrorCode.X, "...")` (from `nimblebrain_server_sdk.errors`) with a message safe to show; `add_error_contract(mcp)` returns it to the caller as an error result. Never return an error as a plain dict: a host and a model score it as a success. 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 diff --git a/README.md b/README.md index af5c0c2..07a981b 100644 --- a/README.md +++ b/README.md @@ -81,22 +81,25 @@ for what every server on NimbleBrain shares. Start with the | 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/) | +| Returns a failure with a code the caller can act on | `add_error_contract`, `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/) | +| Tests what a host sees, on both protocol versions | `Mode`, `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. +write that overwrites or removes). It reports a failure by raising `ServiceError`, and +`add_error_contract`, called once where the server is built, returns it to the caller as an +error result. A tool never returns a dict that describes an error: a host and a model score +that as a success. ```python from fastmcp import FastMCP -from nimblebrain_server_sdk import ADDS -from nimblebrain_server_sdk.errors import ErrorCode, ServiceError, to_tool_error +from nimblebrain_server_sdk import ADDS, add_error_contract +from nimblebrain_server_sdk.errors import ErrorCode, ServiceError mcp = FastMCP("Example") +add_error_contract(mcp) ITEMS: dict[str, str] = {} @@ -105,7 +108,7 @@ ITEMS: dict[str, str] = {} 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.")) + raise ServiceError(ErrorCode.BAD_INPUT, "`name` is empty.") item_id = str(len(ITEMS) + 1) ITEMS[item_id] = name return {"id": item_id, "name": name} @@ -134,24 +137,25 @@ add_skills(mcp, [Path("src/mcp_example/skills/example")]) 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. +handshake. `Mode` is the type of that parameter. `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 nimblebrain_server_sdk.testing import Mode, served_skills from mcp_example.server import mcp @pytest.mark.parametrize("mode", ["auto", "legacy"]) -async def test_the_skill_is_served(mode): +async def test_the_skill_is_served(mode: Mode) -> None: 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 def test_an_empty_item_id_is_bad_input(mode: Mode) -> None: 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 diff --git a/pyproject.toml b/pyproject.toml index 7fc3699..d23b27c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,7 @@ classifiers = [ dependencies = [ "aiohttp>=3.11.0", "fastmcp>=4.0.0", - "nimblebrain-server-sdk>=0.6.1", + "nimblebrain-server-sdk>=0.7,<0.8", "pydantic>=2.0.0", "python-dotenv>=1.0.0", ] diff --git a/src/mcp_example/server.py b/src/mcp_example/server.py index 7c3a782..47653a7 100644 --- a/src/mcp_example/server.py +++ b/src/mcp_example/server.py @@ -24,8 +24,14 @@ from fastmcp import FastMCP 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 nimblebrain_server_sdk import ( + PREVIEW_CHARS, + READS, + add_error_contract, + add_skills, + listing_row, +) +from nimblebrain_server_sdk.errors import ErrorCode, ServiceError from starlette.requests import Request from starlette.responses import JSONResponse @@ -33,7 +39,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 returned with to_tool_error. +# protocol (SEP-2577). A failure the caller must see is a raised ServiceError. logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", @@ -57,6 +63,8 @@ "for tool selection guidance and workflow patterns." ), ) +# A ServiceError a tool raises reaches the caller as an error result with its code. +add_error_contract(mcp) add_skills(mcp, [SKILLS_DIR / "example"]) # Global client instance (lazy initialization) @@ -104,7 +112,9 @@ async def health_check(request: Request) -> JSONResponse: # 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(...))`. +# A tool reports a failure by raising ServiceError, and add_error_contract returns +# it to the caller as an error result. Never return a dict that describes an error: +# a host and a model score it as a success. # ============================================================================ @@ -123,16 +133,12 @@ async def list_items( the whole item. """ if not 1 <= limit <= MAX_LIMIT: - return to_tool_error( - ServiceError(ErrorCode.BAD_INPUT, f"`limit` must be between 1 and {MAX_LIMIT}.") - ) + raise ServiceError(ErrorCode.BAD_INPUT, f"`limit` must be between 1 and {MAX_LIMIT}.") try: client = await get_client() items = await client.list_items(limit=limit) - except ServiceError as e: - return to_tool_error(e) except ExampleAPIError as e: - return to_tool_error(upstream_error(e)) + raise upstream_error(e) from e # A page holds many rows, so an unbounded field leaves each row as a preview. return [ listing_row( @@ -170,10 +176,7 @@ async def get_item( Returns: Item details """ - try: - return await read_item(item_id) - except ServiceError as e: - return to_tool_error(e) + return await read_item(item_id) # ============================================================================ @@ -189,8 +192,9 @@ async def item_resource(item_id: str) -> str: 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. + # add_error_contract covers tool calls. A resource read has no 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/tests/test_server.py b/tests/test_server.py index 63ef5ee..300e93e 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -10,13 +10,13 @@ import pytest from fastmcp import Client from mcp.shared.exceptions import MCPError -from nimblebrain_server_sdk.testing import assert_bounded_rows, served_skills +from nimblebrain_server_sdk.testing import Mode, assert_bounded_rows, served_skills from mcp_example.api_client import ExampleAPIError from mcp_example.server import SKILLS_DIR from tests.conftest import LONG_DESCRIPTION -MODES = ["auto", "legacy"] # 2026-07-28, then 2025-11-25 +MODES: list[Mode] = ["auto", "legacy"] # 2026-07-28, then 2025-11-25 SKILL_URI = "skill://example/SKILL.md" @@ -24,7 +24,7 @@ class TestSkill: """The skill a host reads before it uses the tools.""" - async def test_skill_is_served(self, mcp_server, mode): + async def test_skill_is_served(self, mcp_server, mode: 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} @@ -32,7 +32,7 @@ async def test_skill_is_served(self, mcp_server, mode): assert frontmatter["name"] == "example" assert frontmatter["description"] - async def test_instructions_name_the_skill(self, mcp_server, mode): + async def test_instructions_name_the_skill(self, mcp_server, mode: 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 @@ -40,7 +40,7 @@ async def test_instructions_name_the_skill(self, mcp_server, mode): (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): + async def test_skill_names_every_tool(self, mcp_server, mode: Mode): """The skill covers each tool the server lists.""" async with Client(mcp_server, mode=mode) as client: tools = await client.list_tools() @@ -53,13 +53,13 @@ async def test_skill_names_every_tool(self, mcp_server, mode): class TestToolListing: """What a host learns about the tools before it calls one.""" - async def test_all_tools_listed(self, mcp_server, mode): + async def test_all_tools_listed(self, mcp_server, mode: Mode): """All expected tools appear in tool listing.""" 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): + async def test_every_tool_is_annotated(self, mcp_server, mode: 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() @@ -72,7 +72,7 @@ async def test_every_tool_is_annotated(self, mcp_server, mode): class TestTools: """The tools, called the way a host calls them.""" - async def test_list_items_returns_bounded_rows(self, mcp_server, mock_client, mode): + async def test_list_items_returns_bounded_rows(self, mcp_server, mock_client, mode: 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, mode=mode) as client: @@ -83,7 +83,7 @@ async def test_list_items_returns_bounded_rows(self, mcp_server, mock_client, mo 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): + async def test_get_item_returns_the_whole_item(self, mcp_server, mock_client, mode: 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, mode=mode) as client: @@ -96,7 +96,7 @@ async def test_get_item_returns_the_whole_item(self, mcp_server, mock_client, mo 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): + async def test_a_row_uri_reads_the_whole_item(self, mcp_server, mock_client, mode: 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: @@ -107,13 +107,13 @@ async def test_a_row_uri_reads_the_whole_item(self, mcp_server, mock_client, mod assert json.loads(content.text) == item assert item["description"] == LONG_DESCRIPTION - async def test_the_item_address_is_listed(self, mcp_server, mode): + async def test_the_item_address_is_listed(self, mcp_server, mode: 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): + async def test_a_missing_item_fails_the_read(self, mcp_server, mock_client, mode: 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): @@ -124,7 +124,7 @@ async def test_a_missing_item_fails_the_read(self, mcp_server, mock_client, mode assert "items_v2" not in str(failure.value) -async def call_for_error(mcp_server, mode, tool, arguments): +async def call_for_error(mcp_server, mode: 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) @@ -144,14 +144,16 @@ class TestErrors: ("get_item", {"item_id": " "}, "`item_id` is empty."), ], ) - async def test_a_caller_mistake_is_bad_input(self, mcp_server, mode, tool, arguments, message): + async def test_a_caller_mistake_is_bad_input( + self, mcp_server, mode: 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): + async def test_a_missing_item_is_not_found(self, mcp_server, mock_client, mode: 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): @@ -163,7 +165,7 @@ async def test_a_missing_item_is_not_found(self, mcp_server, mock_client, mode): "upstream_status": 404, } - async def test_a_rate_limit_is_retryable(self, mcp_server, mock_client, mode): + async def test_a_rate_limit_is_retryable(self, mcp_server, mock_client, mode: 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): @@ -172,7 +174,7 @@ async def test_a_rate_limit_is_retryable(self, mcp_server, mock_client, mode): assert error["retryable"] is True assert error["upstream_status"] == 429 - async def test_a_missing_api_key_is_auth_required(self, mcp_server, monkeypatch, mode): + async def test_a_missing_api_key_is_auth_required(self, mcp_server, monkeypatch, mode: 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)