nimblebrain_server_sdk
nimblebrain_server_sdk · install nimblebrain-server-sdk · version 0.7.2
from nimblebrain_server_sdk import ADDS, CHANGES, ErrorContractMiddlewareThe SDK for building MCP servers that run on NimbleBrain.
What a server shares with the host it runs in: the tool annotation hints, the change
announcement its views re-read on, the platform extensions (facets, lifecycle handlers, the
view a record opens in), skills served through the MCP Skills extension
(io.modelcontextprotocol/skills), the bounded row a listing returns, the opaque record id it
mints, and reads of workspace files through ai.nimblebrain/host-resources.
Functions
Section titled “Functions”add_error_contract
Section titled “add_error_contract”def add_error_contract(mcp: FastMCP) -> NoneMake mcp return the error contract for a contract error a tool raises.
Call it once, when the server is built. After it, a tool may let a ServiceError
([db]’s AuthError is one) or a capacity refusal ([db]’s Overloaded)
propagate: the caller receives the same result as return to_tool_error(err) or
return rate_limited_tool_error(err), recorded once. Other exceptions are untouched.
It covers tool calls; a resource read has no in-band error result to return.
It also stops FastMCP logging a traceback for those errors on mcp’s tool calls: each
is recorded once when it is surfaced (service_error, at WARNING for
bad_input), which is the record to alert on. FastMCP’s record is kept for a resource
read, a prompt, and a server that does not have the contract.
add_lifecycle_extension
Section titled “add_lifecycle_extension”def add_lifecycle_extension(mcp: FastMCP) -> LifecycleExtensionAdvertise ai.nimblebrain/lifecycle on mcp and return it, to register handlers on.
Like any platform extension it is advertised in server/discover only, so a host on a
2025-era connection sees no extension and makes no lifecycle calls (spec §2, §6).
add_platform_extension
Section titled “add_platform_extension”def add_platform_extension(mcp: FastMCP, identifier: str, settings: Mapping[str, Any] | None = None) -> PlatformExtensionAdvertise identifier with settings at capabilities.extensions[identifier].
The SDK validates the identifier (a vendor-prefix/name pair), and FastMCP refuses a
second registration of the same one and any registration after the server started.
add_skills
Section titled “add_skills”def add_skills(mcp: FastMCP, skills: Iterable[SkillInput]) -> SkillsExtensionDeclare the skills extension on FastMCP server mcp and serve skills through it.
Every check SEP-2640 places on a skill runs here, so a bad skill fails at import. Like any extension, it is registered where the server is built, before it serves, and once: every skill the server publishes goes in the one call.
announce_resource_list_changed
Section titled “announce_resource_list_changed”async def announce_resource_list_changed(ctx: Context | None = None, *, tool: str | None = None) -> NoneSend notifications/resources/list_changed in the response to the call that wrote.
That call came from the host that holds this workspace, so the notification is scoped to the workspace without the server keeping a map of sessions. The host relays it to this server’s views, which re-read.
Call it only from a write, once the write has committed. A read never calls it: a view re-reads when told the list changed, so a read that announced would have every open view refreshing itself forever.
ctx defaults to the active MCP request’s context. With neither there is no response to
announce in — a tool body called directly, or a write made outside any tool call — and
that is not a failure. Nor is a send that fails: the write is stored either way, and
reporting a stored write as failed would have the agent make it a second time. A view
that misses one catches up on its next read.
tool names the calling tool on that failure’s log line.
facet_count
Section titled “facet_count”def facet_count(count: int) -> strThe body of a facet read: {"count": count} as JSON text.
Raises ValueError for anything but a non-negative integer, because a host treats
any other count as a failed read. Failing here names the server’s own bug instead of
leaving it to show up as a facet that never renders.
facet_meta
Section titled “facet_meta”def facet_meta(level: FacetLevel) -> dict[str, Any]The _meta a facet resource carries: the extension’s marker, holding its level.
The level belongs to the facet, not to a reading, so it is declared once here and never
changes with the count. Raises ValueError for a level the extension does not
define, which a host would read as warning.
lifecycle_meta
Section titled “lifecycle_meta”def lifecycle_meta(event: LifecycleEvent) -> dict[str, Any]The _meta a handler tool carries: the extension’s marker, naming its event.
Raises ValueError for an event the extension does not define, which a host
ignores, so the handler would never be called.
listing_row
Section titled “listing_row”def listing_row(record: Mapping[str, Any], *, omit: Iterable[str] = (), preview: Mapping[str, int] | None = None) -> dict[str, Any]record as a listing row: each omit field dropped, each preview field cut.
A previewed field f leaves the row and comes back as f_preview, at most
preview[f] characters (preview_text), so a reader never mistakes a preview
for the field itself. A None value stays None. A field the record lacks is
skipped, so one call serves records that carry it and records that do not. Every other
key, uri included, is copied unchanged; the record itself is not modified.
Raises TypeError for a previewed value that is neither text nor None, which
is a server bug a preview would hide.
new_prefixed_id
Section titled “new_prefixed_id”def new_prefixed_id(prefix: str) -> str<prefix>_<ulid>: an opaque record id whose prefix names the record’s kind.
prefix is lowercase ASCII letters and digits, in one segment (tk) or several
joined by single underscores (po_cmp). A ULID carries no underscore, so the last
underscore of an id always separates its prefix from its body. Anything else raises
ValueError: an empty prefix, a capital, a hyphen, or a leading, trailing or doubled
underscore.
new_ulid
Section titled “new_ulid”def new_ulid() -> strOne fresh ULID, strictly greater than every ULID minted before it in this process.
preview_text
Section titled “preview_text”def preview_text(text: str, chars: int = PREVIEW_CHARS) -> strtext cut to at most chars characters, ending in … when anything was cut.
record_view_meta
Section titled “record_view_meta”def record_view_meta(view_uri: str) -> dict[str, Any]The _meta a record’s resource template carries to name the view that shows it.
Raises ValueError for anything but a ui:// URI, which a host would ignore and
which would leave the record opening in the server’s first view without a sign of why.
Classes
Section titled “Classes”ErrorContractMiddleware
Section titled “ErrorContractMiddleware”class ErrorContractMiddleware(Middleware)Returns the contract’s tool error for a ServiceError or capacity refusal a tool raises.
HostCapabilityMissing
Section titled “HostCapabilityMissing”class HostCapabilityMissing(capability_key: str, *, protocol_version: str | None = None)Raised by a host-resources call the connection cannot carry.
Either the host did not advertise the capability, or the connection negotiated the
2026-07-28 protocol, which has no channel for a request from a server to its client. The
message says which. Catch it, or check host(ctx).available first, and return a tool
error that tells the agent to pass the content inline instead:
try: result = await host(ctx).read(seed_uri)except HostCapabilityMissing: return to_tool_error( ServiceError( ErrorCode.BAD_INPUT, "This connection cannot read workspace files. Pass the file's contents " "in `seed_data` instead.", ) )protocol_version is the negotiated version when the protocol era is the cause, else
None.
HostResources
Section titled “HostResources”class HostResources(ctx: Context)Bundle-side handle for the host-resources extension.
Construct via the host(ctx) factory rather than directly — the
factory keeps the call site uniform across the SDK.
HostResources.available
Section titled “HostResources.available”available: boolTrue when the host advertised host-resources with read enabled.
This is the common-case probe for read(). For list(), use
list_available instead — a host could advertise list.enabled
without read.enabled (or vice versa), and gating both methods
on a single flag would silently mis-route.
Reads from ClientCapabilities.extensions["ai.nimblebrain/host-resources"],
falling back to the legacy experimental slot for hosts that
haven’t migrated to the spec-blessed extensions field yet.
Returns False on any malformed shape so a buggy host can’t
crash a bundle’s availability probe, and False on the 2026-07-28
protocol era, which has no back-channel for the host request.
HostResources.list
Section titled “HostResources.list”async def list(*, scheme: str | None = None, mime_type: str | None = None, tags: builtins.list[str] | None = None) -> ListResourcesResultList workspace resources, optionally filtered.
Filters are AND-combined (resources must match every constraint).
Pagination via cursor is not supported in v1 — the platform
returns the full set in one response and rejects non-empty
cursors with -32602.
Raises HostCapabilityMissing if the host hasn’t advertised
the extension with list.enabled — check list_available
before calling, or catch and fall back. Wire errors propagate as
MCPError (see read).
HostResources.list_available
Section titled “HostResources.list_available”list_available: boolTrue when the host advertised host-resources with list enabled.
v1 hosts always ship read and list enabled together, so this
will move in lockstep with available in practice. The split
exists because the capability shape allows independent flags and
the SDK shouldn’t bake the lockstep assumption in — a future host
that disables one method (e.g. read-only inventory listing) gets
correct behaviour for free.
HostResources.read
Section titled “HostResources.read”async def read(uri: str) -> ReadResourceResultRead a single workspace resource by URI.
Raises HostCapabilityMissing if the host hasn’t advertised the
extension with read.enabled, or the connection negotiated the
2026-07-28 protocol — check available first, or catch and fall
back to a structured tool error (the Level-C pattern).
Raises mcp.shared.exceptions.MCPError for wire-level errors (match on .code):
-32002 Resource not found(also: cross-workspace lookup)-32004 Rate limited(withretryAfterMsinerror.data)-32005 Response too large(withsize,maxSize)-32602 Invalid params(unsupported scheme)
HostResources.supports_scheme
Section titled “HostResources.supports_scheme”def supports_scheme(scheme: str) -> boolTrue when the host advertised the given URI scheme.
The host-resources capability includes a schemes allowlist
(["files"] in v1). Bundles check this before issuing a read
against an entities:// URI etc., since the platform will
return -32602 Invalid params for any scheme outside the
allowlist.
LifecycleExtension
Section titled “LifecycleExtension”class LifecycleExtension()The advertised extension, and the record of which tool handles which event.
LifecycleExtension.handler
Section titled “LifecycleExtension.handler”def handler(event: LifecycleEvent, *, name: str | None = None, title: str | None = None, description: str | None = None, annotations: ToolAnnotations | None = None, meta: dict[str, Any] | None = None) -> Callable[[F], F]Register the decorated function as this server’s handler for event.
The tool is an ordinary tool carrying lifecycle_meta merged into meta.
Raises ValueError, before anything is registered, for a second handler for
event, for a handler whose input schema requires a property, and for a meta
that already carries the marker.
LifecycleExtension.handlers
Section titled “LifecycleExtension.handlers”handlers: dict[LifecycleEvent, str]The tool registered for each event, by event.
MCPServerSkillsExtension
Section titled “MCPServerSkillsExtension”class MCPServerSkillsExtension(skills: Iterable[SkillInput])SEP-2640 skills for an mcp SDK MCPServer.
server = MCPServer("name", extensions=[MCPServerSkillsExtension([skill_dir])])PlatformExtension
Section titled “PlatformExtension”class PlatformExtension(identifier: str, settings: Mapping[str, Any] | None = None)An extension that only advertises: an identifier and its settings, no methods.
What a platform extension serves rides the primitives a peer already calls (a marked
resource, a tool), so the advertisement is the whole contract. An extension that serves
methods of its own subclasses ServerExtension directly.
SkillDefinition
Section titled “SkillDefinition”class SkillDefinition(path: str, files: Mapping[str, str | bytes], *, scheme: str = 'skill')A skill’s files, validated against SEP-2640 at construction.
path is the skill path (tasks, or acme/billing/refunds); its last
segment must equal the frontmatter name. files maps each file’s path
relative to the skill root to its content and must include SKILL.md. Use
this directly for a skill whose files are generated or packaged; use
from_directory for a skill that is a directory on disk.
Content that decodes as UTF-8 is served as a text resource, anything else as a blob. Either way the digest covers the raw bytes, which is what a host hashes after decoding the text or the base64.
SkillDefinition.entry
Section titled “SkillDefinition.entry”def entry() -> dict[str, Any]This skill’s skills/list / skills/get entry, in wire form.
SkillDefinition.from_directory
Section titled “SkillDefinition.from_directory”def from_directory(directory: str | PathLike[str], *, path: str | None = None, scheme: str = 'skill') -> SkillDefinitionLoad every file under directory (dotfiles and __pycache__ excluded).
path defaults to the directory’s name, which the Agent Skills
specification requires to equal the skill’s name.
SkillDefinition.resource_metadata
Section titled “SkillDefinition.resource_metadata”def resource_metadata(file: SkillFile) -> dict[str, Any]name/description/mimeType for a file’s resource.
SKILL.md takes its name and description from the frontmatter
(SEP-2640 “Resource Metadata”); other files are named by their path.
SkillsExtension
Section titled “SkillsExtension”class SkillsExtension(skills: Iterable[SkillInput])SEP-2640 skills for a FastMCP server.
mcp.add_extension(SkillsExtension([Path(__file__).parent / "skills" / "tasks"]))Registering it declares io.modelcontextprotocol/skills, serves
skills/list and skills/get, and registers every skill file as a resource.
Constants
Section titled “Constants”ADDS = ToolAnnotations(read_only_hint=False, destructive_hint=False)A write that loses nothing already there.
CHANGES
Section titled “CHANGES”CHANGES = ToolAnnotations(read_only_hint=False, destructive_hint=True)A write that overwrites, removes, or acts on what is already there.
FACET_LEVELS
Section titled “FACET_LEVELS”FACET_LEVELS = ('critical', 'warning', 'info')FacetLevel
Section titled “FacetLevel”FacetLevel = Literal['critical', 'warning', 'info']FACETS_EXTENSION_ID
Section titled “FACETS_EXTENSION_ID”FACETS_EXTENSION_ID = 'ai.nimblebrain/facets'HOST_RESOURCES_CAPABILITY_KEY
Section titled “HOST_RESOURCES_CAPABILITY_KEY”HOST_RESOURCES_CAPABILITY_KEY = 'ai.nimblebrain/host-resources'HOST_RESOURCES_LIST_METHOD
Section titled “HOST_RESOURCES_LIST_METHOD”HOST_RESOURCES_LIST_METHOD = 'ai.nimblebrain/resources/list'HOST_RESOURCES_READ_METHOD
Section titled “HOST_RESOURCES_READ_METHOD”HOST_RESOURCES_READ_METHOD = 'ai.nimblebrain/resources/read'INVALID_PARAMS
Section titled “INVALID_PARAMS”INVALID_PARAMS = -32602LIFECYCLE_EVENTS
Section titled “LIFECYCLE_EVENTS”LIFECYCLE_EVENTS = ('ready', 'removing')LIFECYCLE_EXTENSION_ID
Section titled “LIFECYCLE_EXTENSION_ID”LIFECYCLE_EXTENSION_ID = 'ai.nimblebrain/lifecycle'LifecycleEvent
Section titled “LifecycleEvent”LifecycleEvent = Literal['ready', 'removing']PREVIEW_CHARS
Section titled “PREVIEW_CHARS”PREVIEW_CHARS = 200A preview’s default length in characters: enough to recognise a record, not to read it.
RATE_LIMITED
Section titled “RATE_LIMITED”RATE_LIMITED = -32004READS = ToolAnnotations(read_only_hint=True)Changes nothing a view shows. A read that records an audit row or refreshes provider state on the way in is still a read.
RECORD_VIEW_META
Section titled “RECORD_VIEW_META”RECORD_VIEW_META = 'ai.nimblebrain/view'RESOURCE_NOT_FOUND
Section titled “RESOURCE_NOT_FOUND”RESOURCE_NOT_FOUND = -32002RESPONSE_TOO_LARGE
Section titled “RESPONSE_TOO_LARGE”RESPONSE_TOO_LARGE = -32005SKILLS_EXTENSION_ID
Section titled “SKILLS_EXTENSION_ID”SKILLS_EXTENSION_ID = 'io.modelcontextprotocol/skills'