Skip to content
This repository was archived by the owner on Nov 27, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 15 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {}

Expand All @@ -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}
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Expand Down
36 changes: 20 additions & 16 deletions src/mcp_example/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,22 @@

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

from mcp_example.api_client import ExampleAPIError, ExampleClient

# 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",
Expand All @@ -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)
Expand Down Expand Up @@ -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.
# ============================================================================


Expand All @@ -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(
Expand Down Expand Up @@ -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)


# ============================================================================
Expand All @@ -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


Expand Down
Loading
Loading