Server API Reference¶
server
¶
MCP server decorator API.
McpServerModule
¶
Namespace for the :meth:for_root class factory.
for_root
staticmethod
¶
for_root(
server_cls,
*,
transport="ws",
server_info=None,
capabilities=None,
providers=None,
imports=None,
exports=None,
log_level="debug",
mounts=None,
proxies=None,
instrument_otel=None,
)
Build a Lauren @module that wires server_cls into the MCP stack.
Parameters¶
server_cls:
A class decorated with @mcp_server. Must have a
__mcp_server_meta__ attribute attached by the decorator.
transport:
"ws" — WebSocket only (default).
"sse" — legacy HTTP+SSE only (MCP 2024-11-05).
"streamable" — Streamable HTTP only (MCP 2025-03-26).
"both" — WebSocket + legacy HTTP+SSE.
"all" — WebSocket + Streamable HTTP. (Legacy SSE and
Streamable HTTP share the POST / route, so they cannot be
mounted together on one path.)
server_info:
Optional :class:~lauren_mcp._types.Implementation describing this
server; defaults to Implementation(name=server_cls.__name__,
version="1.0.0").
capabilities:
Optional :class:~lauren_mcp._types.ServerCapabilities override.
When None the capabilities are inferred from which
@mcp_tool / @mcp_resource / @mcp_prompt methods the
class exposes (with listChanged: True and logging enabled).
providers:
Extra Lauren providers to add to the generated module. Use this
to make services visible to server_cls via constructor injection.
imports:
Extra Lauren @module classes to import into the generated module.
exports:
Extra types to export from the generated module.
log_level:
Minimum severity for client-bound log notifications emitted via
ctx.log() ("debug" | "info" | "warning" |
"error"). Clients may raise it at runtime with
logging/setLevel.
mounts:
[(OtherServerCls, "prefix_"), ...] — expose another
@mcp_server class's tools / resources / prompts through this
server, names prefixed to avoid collisions. Colliding names
raise :class:~lauren_mcp.McpToolNameCollision at startup.
proxies:
[(client, "prefix_"), ...] — connect each
:class:~lauren_mcp.McpClientProtocol at startup and re-export
the remote server's tools under the prefix. Calls are forwarded
over the client; connections close at shutdown.
instrument_otel:
True — always instrument with OpenTelemetry (raises
ImportError if opentelemetry-api is not installed).
False — never instrument.
None — auto-detect: instrument if opentelemetry-api is
installed (default).
Returns¶
type
A @module class ready to be imported by the root application
module.
Raises¶
TypeError
If server_cls was not decorated with @mcp_server.
ValueError
If transport is not one of the accepted spellings.
Source code in src/lauren_mcp/server/_module.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 | |
mcp_server
¶
Class decorator that marks a class as an MCP server.
Applies @injectable(scope=Scope.SINGLETON) from Lauren so the class
participates in DI, and attaches :class:McpServerMeta as an attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The mount path for the MCP server endpoint (e.g. |
required |
transport
|
str
|
One of |
'ws'
|
Source code in src/lauren_mcp/server/_decorators.py
mcp_tool
¶
mcp_tool(
*,
name=None,
description=None,
title=None,
annotations=None,
timeout=None,
tags=None,
meta=None,
output_schema=None,
structured_output=None,
strict=True,
)
Method decorator that exposes a coroutine as an MCP tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Override the tool name (defaults to the method name). |
None
|
description
|
str | None
|
Override the tool description (defaults to docstring). |
None
|
title
|
str | None
|
Human-readable display name shown in client UIs (distinct from
the machine-readable |
None
|
annotations
|
ToolAnnotations | None
|
Behavioural hints (:class: |
None
|
timeout
|
float | None
|
Per-call execution deadline in seconds; exceeding it fails the call with an internal error. |
None
|
tags
|
frozenset[str] | set[str] | None
|
Categorical tags included in the tool's |
None
|
meta
|
dict[str, Any] | None
|
Opaque metadata forwarded to clients under |
None
|
output_schema
|
Any
|
JSON Schema dict or Pydantic model class describing the
tool's structured output; advertised as |
None
|
structured_output
|
bool | None
|
Control auto-detection of output schema. |
None
|
strict
|
bool
|
When |
True
|
Source code in src/lauren_mcp/server/_decorators.py
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 | |
mcp_resource
¶
mcp_resource(
uri_template,
*,
name=None,
description=None,
title=None,
mime_type=None,
annotations=None,
)
Method decorator that exposes a coroutine as an MCP resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri_template
|
str
|
A URI template with |
required |
name
|
str | None
|
Resource name (defaults to the method name). |
None
|
description
|
str | None
|
Human-readable description (defaults to docstring). |
None
|
title
|
str | None
|
Human-readable display name shown in client UIs. |
None
|
mime_type
|
str | None
|
Optional MIME type hint (e.g. |
None
|
annotations
|
ResourceAnnotations | None
|
Audience and priority hints (:class: |
None
|
Source code in src/lauren_mcp/server/_decorators.py
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 | |
mcp_prompt
¶
Method decorator that exposes a coroutine as an MCP prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Prompt name (defaults to the method name). |
None
|
description
|
str | None
|
Human-readable description (defaults to docstring). |
None
|
title
|
str | None
|
Human-readable display name shown in client UIs. |
None
|
Source code in src/lauren_mcp/server/_decorators.py
SchemaBuilder
¶
Builds JSON Schema fragments from Python type annotations.
One builder instance is shared across all parameters of a function so
Pydantic model definitions are accumulated once into defs and can be
attached to the top-level schema as $defs.
Source code in src/lauren_mcp/server/_schema.py
build
¶
Return a JSON Schema fragment for annotation.
Unknown types degrade to {} (unconstrained) rather than raising.
Source code in src/lauren_mcp/server/_schema.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
FileResource
¶
Expose a local file as a static MCP resource.
MIME type is auto-detected from the file extension when mime_type is
omitted. Files whose MIME type starts with "text/" or is one of the
common text-like types (application/json, application/xml) are
served as UTF-8 strings; everything else is returned as a
:class:~lauren_mcp._types.BlobResource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Absolute or relative path to the file on disk. |
required |
uri
|
str
|
The URI the resource is reachable under (e.g.
|
required |
name
|
str | None
|
Resource name for |
None
|
description
|
str | None
|
Human-readable description (optional). |
None
|
mime_type
|
str | None
|
Explicit MIME type; auto-detected from extension when
|
None
|
Source code in src/lauren_mcp/server/_builtin_resources.py
read
async
¶
Read the file and return text or :class:BlobResource.
Source code in src/lauren_mcp/server/_builtin_resources.py
as_mcp_resource_meta
¶
Return an :class:McpResourceMeta whose method_name points to
read.
Source code in src/lauren_mcp/server/_builtin_resources.py
HttpResource
¶
HttpResource(
url,
uri,
*,
name=None,
description=None,
mime_type=None,
headers=None,
timeout=30.0,
)
Fetch an HTTP URL and expose the response body as an MCP resource.
Requires the [http] extra (httpx).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The upstream URL to fetch on each |
required |
uri
|
str
|
The URI the resource is reachable under. |
required |
name
|
str | None
|
Resource name (defaults to url). |
None
|
description
|
str | None
|
Human-readable description (optional). |
None
|
mime_type
|
str | None
|
Explicit MIME type; taken from the response
|
None
|
headers
|
dict[str, str] | None
|
Extra HTTP headers forwarded with every request. |
None
|
timeout
|
float
|
HTTP request timeout in seconds (default 30.0). |
30.0
|
Source code in src/lauren_mcp/server/_builtin_resources.py
read
async
¶
Fetch the upstream URL and return its body.
Source code in src/lauren_mcp/server/_builtin_resources.py
DirectoryResource
¶
DirectoryResource(
path,
uri,
*,
name=None,
description=None,
pattern="*",
recursive=False,
include_hidden=False,
)
List files in a directory as a JSON array resource.
Returns a JSON-serialised list of relative file paths matching pattern.
The response MIME type is always "application/json".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Root directory to list. |
required |
uri
|
str
|
The URI the resource is reachable under. |
required |
name
|
str | None
|
Resource name (defaults to the directory's basename). |
None
|
description
|
str | None
|
Human-readable description (optional). |
None
|
pattern
|
str
|
Glob pattern relative to path (default |
'*'
|
recursive
|
bool
|
When |
False
|
include_hidden
|
bool
|
When |
False
|
Source code in src/lauren_mcp/server/_builtin_resources.py
read
async
¶
Return JSON array of relative paths matching the pattern.
Source code in src/lauren_mcp/server/_builtin_resources.py
McpToolContext
dataclass
¶
McpToolContext(
tool_name,
tool_use_id=None,
headers=None,
execution_context=None,
session_id=None,
metadata=dict(),
state=dict(),
extras=dict(),
lifespan_context=dict(),
_progress_token=None,
_send_notification=None,
_client_rpc=None,
_client_capabilities=None,
_log_level_state=None,
_cancel_event=None,
)
Context injected into an @mcp_tool method when a parameter is
annotated with McpToolContext.
The object is immutable so tool authors cannot accidentally mutate shared
transport state. The state bag is mutable per-call scratch space and
extras is the extension bag for integrations (lauren-ai stores its
AgentContext under extras["agent_context"]).
cancel_requested
property
¶
An asyncio.Event set when the client cancels this call.
The event is created lazily on first access and stored in the
(normally immutable) dataclass via object.__setattr__. This is
safe because the event is local to this call instance and is only
written once (by the dispatcher, before task.cancel() is called).
Tools should treat this as a read-only hint: check
cancel_requested.is_set() between work units and return early for
graceful shutdown. The containing asyncio.Task will still be
hard-cancelled shortly after the event fires.
.. note::
The event is never set on the legacy HTTP+SSE transport (which
does not implement $/cancelRequest).
report_progress
async
¶
Send notifications/progress to the client.
No-op when the client did not supply a progressToken in the
tools/call request, or when the transport has no notification
channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
progress
|
float | int
|
Current progress value (e.g. number of items processed). |
required |
total
|
float | int | None
|
Optional upper bound. When omitted the client treats progress as indeterminate. |
None
|
message
|
str | None
|
Optional human-readable status string displayed alongside
the progress indicator (e.g. |
None
|
Source code in src/lauren_mcp/_server/_context.py
log
async
¶
Send a structured notifications/message log entry to the client.
Dropped silently when below the server's minimum level or when the transport has no notification channel.
Source code in src/lauren_mcp/_server/_context.py
notice
async
¶
Send a notice-level log notification.
Use for normal but significant conditions that operators should be aware of (e.g. a configuration override taking effect, a fallback path used).
Source code in src/lauren_mcp/_server/_context.py
critical
async
¶
Send a critical-level log notification.
Use for conditions that require immediate attention but have not yet caused complete service failure (e.g. a primary data source is down and a fallback is active).
Source code in src/lauren_mcp/_server/_context.py
sample
async
¶
sample(
messages,
*,
max_tokens=1024,
system_prompt=None,
temperature=None,
stop_sequences=None,
model_preferences=None,
include_context="none",
result_type=None,
tools=None,
tool_choice=None,
max_tool_iterations=10,
)
Ask the connected MCP client to run an LLM call on our behalf.
Returns a :class:CreateMessageResult, or — when result_type is a
Pydantic model class — an instance of that model parsed from the
reply text.
When tools is supplied the client's LLM may respond with a
ToolUseContent block instead of a TextContent block.
ctx.sample() does not execute tools automatically. The caller
is responsible for handling ToolUseContent responses and building
the agentic loop.
Parameters¶
tools:
Tool descriptors to pass to the LLM. Each entry may be a
:class:~lauren_mcp._types.ToolSchema, a
:class:~lauren_mcp.server._meta.McpToolMeta (auto-converted), or a
raw dict with name, description, and inputSchema keys.
None means no tools are passed (single-turn text/image only).
tool_choice:
Forwarded to the client as-is. None omits the field (client default).
max_tool_iterations:
Advisory upper bound on agentic loop iterations passed to the client
in CreateMessageParams.metadata["max_tool_iterations"]. Default: 10.
Raises¶
McpSamplingNotAvailable
Client did not advertise sampling capability, or did not advertise
tools support within sampling when tools= is supplied, or
the transport does not support server-to-client requests.
Source code in src/lauren_mcp/_server/_context.py
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 | |
elicit
async
¶
Ask the connected MCP client to prompt its user for input.
response_type may be None (approval only), str, bool,
int, float, a Literal[...], an Enum subclass,
list[str] (multi-select string array), or a flat Pydantic model /
dataclass / TypedDict whose fields are all of the above scalar types.
Raises :class:McpElicitationNotAvailable when the client did not
advertise the elicitation capability or the transport cannot carry
server-to-client requests (legacy SSE).
Source code in src/lauren_mcp/_server/_context.py
elicit_url
async
¶
Direct the user to an external URL and await completion.
The server sends elicitation/create with requestedUrl (and
elicitationId) rather than requestedSchema. The client opens
the URL in a browser; the user completes the external flow; the client
responds with {"action": "accept"} or {"action": "cancel"}.
Parameters¶
message: Human-readable prompt shown to the user before the URL is opened. url: The URL to open. elicitation_id: An opaque string identifying this elicitation instance. Auto-generated as a UUID4 hex string when not provided.
Returns¶
UrlElicitResult
action is "accept" (flow completed) or "cancel"
(user dismissed or flow was abandoned).
Raises¶
McpUrlElicitationNotAvailable
Client did not advertise the urlElicitation sub-capability,
elicitation capability is absent, or the transport does not
support server-to-client requests (e.g. legacy HTTP+SSE).
Source code in src/lauren_mcp/_server/_context.py
McpCatalogManager
¶
SINGLETON holding the live tool / resource / prompt catalogue.
The catalogue is seeded from decorator metadata at startup and can be
mutated at runtime. Every mutation after :meth:set_broadcast_fn fires
the matching notifications/*/list_changed broadcast.
Source code in src/lauren_mcp/_server/_catalog.py
set_broadcast_fn
¶
ResourceSubscriptionManager
¶
SINGLETON that tracks per-URI subscriptions and broadcasts update events.
Session keys come from :class:~lauren_mcp._server._registry.McpConnectionRegistry
(WS transport) or the session_id allocated by
:class:~lauren_mcp._server._session.SseSessionStore /
:class:~lauren_mcp._server._streamable.StreamableSessionStore.
Source code in src/lauren_mcp/_server/_subscriptions.py
subscription_count
property
¶
Total number of active subscriptions across all URIs.
subscribe
¶
Register send_fn as the delivery channel for session_key on uri.
unsubscribe
¶
Remove one subscription. No-op if not present.
Source code in src/lauren_mcp/_server/_subscriptions.py
unsubscribe_all
¶
Remove all subscriptions for session_key (called on disconnect).
Source code in src/lauren_mcp/_server/_subscriptions.py
get_subscribers
¶
notify_updated
async
¶
Broadcast notifications/resources/updated to all subscribers of uri.
Source code in src/lauren_mcp/_server/_subscriptions.py
EventStore
¶
Bases: ABC
Abstract store for SSE event persistence and replay.
Implementations must be thread-safe if the event loop runs in a thread pool; for asyncio single-loop deployments this is not required.
store_event
abstractmethod
async
¶
Persist a single SSE event for session_id.
Parameters¶
session_id:
The Streamable HTTP session identifier.
event_id:
The assigned id: field value, e.g. "sess123:7".
data:
The raw data: payload (JSON string).
Source code in src/lauren_mcp/_server/_event_store.py
replay_events_after
abstractmethod
async
¶
Replay all stored events after last_event_id for session_id.
Calls send(event_id, data) for each replayed event in order.
Parameters¶
session_id:
The session whose events should be replayed.
last_event_id:
The last event ID the client received, or None to replay
all stored events from the beginning.
send:
Async callback invoked once per replayed event.
Source code in src/lauren_mcp/_server/_event_store.py
InMemoryEventStore
¶
Bases: EventStore
In-memory event store for single-process deployments.
Events are stored in a per-session bounded deque. Older events are dropped when the deque reaches max_events to prevent unbounded memory growth.
Parameters¶
max_events: Maximum number of events retained per session. Defaults to 1000.
Source code in src/lauren_mcp/_server/_event_store.py
evict_session
¶
TransportSecuritySettings
dataclass
¶
TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=list(),
allowed_origins=list(),
)
Host/Origin validation settings for HTTP MCP transports.
Parameters¶
enable_dns_rebinding_protection:
Master switch. When False the guard is a no-op.
allowed_hosts:
Accepted Host header values. Each entry may be an exact host
("example.com") or a host with a wildcard port
("example.com:*"). "localhost" and "127.0.0.1" are
always implicitly allowed when the list is empty.
allowed_origins:
Accepted Origin header values for cross-origin POST requests.
An empty list means only same-origin (i.e. requests with no
Origin header or an Origin matching an allowed_hosts
entry pass through).