Skip to content

Plugin & Configuration API

API reference for the LitestarMCP plugin, the standalone MCP application wrapper, MCPConfig and its nested configuration dataclasses (MCPOptKeys, MCPTaskConfig, MCPSkillsConfig), tool-call lifecycle hook protocols, and the Streamable HTTP MCPController.

For architectural guidance and configuration examples, see Configuration & Route Filtering and Standalone MCP Applications.


Plugin & Standalone Application

LitestarMCP

Bases: InitPluginProtocol, CLIPlugin

Litestar plugin for Model Context Protocol integration.

Attributes:

Name Type Description
configMCPConfig

Get the plugin configuration.

registryRegistry

Get the central registry.

task_storeMCPTaskStore | None

Get the task store.

skill_catalogSkillCatalog | None

Get the skill catalog.

discovered_toolsdict[str, BaseRouteHandler]

Get discovered MCP tools.

discovered_resourcesdict[str, BaseRouteHandler]

Get discovered MCP resources.

discovered_promptsdict[str, PromptRegistration]

Get discovered MCP prompts.

register_dynamic_handler

register_dynamic_handler(handler)

Register a dynamic route handler on the plugin.

This is typically used by the wrapper class to register decorated tools and resources.

register_tool

register_tool(tool, *, guards=None, dependencies=None)

Register a Tool instance with the MCP plugin.

on_cli_init

on_cli_init(cli)

Configure CLI commands for MCP operations.

on_app_init

on_app_init(app_config)

Initialize the MCP integration when the Litestar app starts.

on_startup

on_startup(app)

Perform discovery after app is fully initialized and routes are built.

on_shutdown

on_shutdown(app)

Clean up resources on application shutdown.

MCP

A class that simplifies Model Context Protocol application setup.

This provides decorators and programmatic server execution for standalone applications.

Attributes:

Name Type Description
pluginLitestarMCP
Default: found_plugin
appLitestar

Get the Litestar application instance.

tool

tool(
    name=None,
    *,
    after_request=None,
    after_response=None,
    background=None,
    before_request=None,
    cache=False,
    cache_control=None,
    cache_key_builder=None,
    dependencies=None,
    dto=Empty,
    etag=None,
    exception_handlers=None,
    guards=None,
    media_type=None,
    middleware=None,
    route_name=None,
    opt=None,
    request_class=None,
    response_class=None,
    response_cookies=None,
    response_headers=None,
    return_dto=Empty,
    signature_namespace=None,
    status_code=None,
    sync_to_thread=None,
    content_encoding=None,
    content_media_type=None,
    deprecated=False,
    description=None,
    include_in_schema=Empty,
    operation_class=Operation,
    operation_id=None,
    raises=None,
    response_description=None,
    responses=None,
    security=None,
    summary=None,
    tags=None,
    type_decoders=None,
    type_encoders=None,
    **kwargs,
)

Decorator to register a function as an MCP tool.

This dynamically wraps the function inside a Litestar route handler and registers it to the plugin. Additional keyword arguments are passed through to Litestar's post() route decorator.

resource

resource(
    uri,
    *,
    name=None,
    mime_type=None,
    after_request=None,
    after_response=None,
    background=None,
    before_request=None,
    cache=False,
    cache_control=None,
    cache_key_builder=None,
    dependencies=None,
    dto=Empty,
    etag=None,
    exception_handlers=None,
    guards=None,
    media_type=None,
    middleware=None,
    route_name=None,
    opt=None,
    request_class=None,
    response_class=None,
    response_cookies=None,
    response_headers=None,
    return_dto=Empty,
    signature_namespace=None,
    status_code=None,
    sync_to_thread=None,
    content_encoding=None,
    content_media_type=None,
    deprecated=False,
    description=None,
    include_in_schema=Empty,
    operation_class=Operation,
    operation_id=None,
    raises=None,
    response_description=None,
    responses=None,
    security=None,
    summary=None,
    tags=None,
    type_decoders=None,
    type_encoders=None,
    **kwargs,
)

Decorator to register a function as an MCP resource.

This dynamically wraps the function inside a Litestar route handler and registers it to the plugin. Additional keyword arguments are passed through to Litestar's get() route decorator.

prompt

prompt(
    name=None,
    *,
    after_request=None,
    after_response=None,
    background=None,
    before_request=None,
    cache=False,
    cache_control=None,
    cache_key_builder=None,
    dependencies=None,
    dto=Empty,
    etag=None,
    exception_handlers=None,
    guards=None,
    media_type=None,
    middleware=None,
    route_name=None,
    opt=None,
    request_class=None,
    response_class=None,
    response_cookies=None,
    response_headers=None,
    return_dto=Empty,
    signature_namespace=None,
    status_code=None,
    sync_to_thread=None,
    content_encoding=None,
    content_media_type=None,
    deprecated=False,
    description=None,
    include_in_schema=Empty,
    operation_class=Operation,
    operation_id=None,
    raises=None,
    response_description=None,
    responses=None,
    security=None,
    summary=None,
    tags=None,
    type_decoders=None,
    type_encoders=None,
    **kwargs,
)

Decorator to register a function as an MCP prompt.

This dynamically wraps the function inside a Litestar route handler and registers it to the plugin. Additional keyword arguments are passed through to Litestar's get() route decorator.

run

run(transport='streamable-http', **kwargs)

Run the MCP server using the specified transport.

Parameters:

Name Type Description Default
transport Literal['streamable-http', 'stdio']

The transport to use ("streamable-http" or "stdio").

'streamable-http'
**kwargs Any

Arguments passed to the runner.

{}

Configuration Models

MCPConfig

Configuration for the Litestar MCP Plugin.

The plugin uses Litestar's opt attribute to discover routes marked for MCP exposure. Server name and version are derived from the Litestar app's OpenAPI configuration.

Parameters:

Name Type Description Default
base_path str

Base path for MCP API endpoints.

'/mcp'
include_in_schema bool

Whether to include MCP routes in OpenAPI schema generation.

False
name str | None

Optional override for server name; defaults to the OpenAPI title.

None
instructions str | None

Optional server-level instructions returned in the MCP initialize response.

None
guards list[Any] | None

Optional list of Litestar guards protecting MCP endpoints.

None
allowed_origins list[str] | None

Exact additional Origin values to accept alongside the request origin.

None
include_operations list[str] | None

Optional allowlist of operation names to expose over MCP.

None
exclude_operations list[str] | None

Optional denylist of operation names to hide from MCP.

None
include_tags list[str] | None

Optional allowlist of route handler tags to expose over MCP.

None
exclude_tags list[str] | None

Optional denylist of route handler tags to hide from MCP.

None
tasks bool | MCPTaskConfig | None

Optional task configuration or True to enable the default in-memory task implementation.

None
skills MCPSkillsConfig | None

Optional Skills over MCP configuration; None leaves the extension disabled.

None
opt_keys MCPOptKeys

Configurable names for the handler.opt keys read by the plugin.

Downstream apps can rename any key to avoid collisions with other plugins or app-specific conventions. All fields default to mcp_<purpose> and the pattern mirrors litestar.security.jwt.auth.JWTAuth.exclude_opt_key.

<dynamic>
cache_ttl_ms int

Cache duration in milliseconds for list responses (0 disables caching).

0
cache_scope Literal['private', 'public']

Cache visibility scope ("private" or "public").

'private'
subscription_max_streams int

Maximum concurrent SSE subscription streams permitted by the server.

10000
subscription_keepalive_seconds float

Keep-alive ping interval in seconds for active SSE subscription streams.

15.0
stream_queue_capacity int

Maximum queued notifications per stream before producers await capacity.

256
stream_cleanup_timeout float

Positive finite seconds allowed for cooperative progress producer cleanup after its response ends.

5.0
subscription_channels Any | None

Optional Litestar ChannelsPlugin backend used to fan out subscription notifications.

None
list_page_size int

Positive integer page size for tools/list, resources/list, resources/templates/list, skills/list, prompts/list, and resources/directory/read.

100
before_tool_call BeforeToolCallHook | None

Optional callback invoked once before each tools/call dispatch, after the synthesized request is built and before guards run.

None
after_tool_call AfterToolCallHook | None

Optional callback invoked once after each tools/call dispatch with either the result or exception and elapsed duration in seconds.

None
max_blob_bytes int | None

Maximum raw byte length for base64-embedded MCP blobs (None disables the cap).

26214400
route_opt dict[str, Any] | None

Optional route opt mapping applied to the mounted MCP router and merged into the JSON-RPC handler's opt.

None
prompt_controllers Sequence[type[Any]]

Optional sequence of PromptController classes or instances to register on startup.

()
skill_controllers Sequence[type[Any]]

Optional sequence of SkillController classes or instances to register on startup.

()
infer_http_method_annotations bool

Automatically infer default MCP ToolAnnotations hints (readOnlyHint, destructiveHint, idempotentHint) from the route handler's HTTP method when not explicitly overridden.

True
max_tool_description_length int | None

Optional maximum character length for tool descriptions enforced during tool-spec validation.

None
max_param_description_length int | None

Optional maximum character length for input parameter descriptions enforced during tool-spec validation.

None
max_output_field_description_length int | None

Optional maximum character length for output schema property descriptions enforced during tool-spec validation.

None

Attributes:

Name Type Description
base_pathstr

Base path for MCP API endpoints.

include_in_schemabool

Whether to include MCP routes in OpenAPI schema generation.

namestr | None

Optional override for server name; defaults to the OpenAPI title.

instructionsstr | None

Optional server-level instructions returned in the MCP initialize response.

guardslist[Any] | None

Optional list of Litestar guards protecting MCP endpoints.

allowed_originslist[str] | None

Exact additional Origin values to accept alongside the request origin.

include_operationslist[str] | None

Optional allowlist of operation names to expose over MCP.

exclude_operationslist[str] | None

Optional denylist of operation names to hide from MCP.

include_tagslist[str] | None

Optional allowlist of route handler tags to expose over MCP.

exclude_tagslist[str] | None

Optional denylist of route handler tags to hide from MCP.

tasksbool | MCPTaskConfig | None

Optional task configuration or True to enable the default in-memory task implementation.

skillsMCPSkillsConfig | None

Optional Skills over MCP configuration; None leaves the extension disabled.

opt_keysMCPOptKeys

Configurable handler.opt key names inspected by the plugin.

cache_ttl_msint

Cache duration in milliseconds for list responses (0 disables caching).

cache_scopeLiteral['private', 'public']

Cache visibility scope ("private" or "public").

subscription_max_streamsint

Maximum concurrent SSE subscription streams permitted by the server.

subscription_keepalive_secondsfloat

Keep-alive ping interval in seconds for active SSE subscription streams.

stream_queue_capacityint

Maximum queued notifications per stream before producers await capacity.

stream_cleanup_timeoutfloat

Positive finite seconds allowed for cooperative progress producer cleanup after its response ends.

subscription_channelsAny | None

Optional Litestar ChannelsPlugin backend used to fan out subscription notifications.

list_page_sizeint

Positive integer page size for tools/list, resources/list, resources/templates/list, skills/list, prompts/list, and resources/directory/read.

before_tool_callBeforeToolCallHook | None

Optional callback invoked once before each tools/call dispatch, after the synthesized request is built and before guards run.

after_tool_callAfterToolCallHook | None

Optional callback invoked once after each tools/call dispatch with either the result or exception and elapsed duration in seconds.

max_blob_bytesint | None

Maximum raw byte length for base64-embedded MCP blobs (None disables the cap).

route_optdict[str, Any] | None

Optional route opt mapping applied to the mounted MCP router and merged into the JSON-RPC handler's opt.

prompt_controllersSequence[type[Any]]

Optional sequence of PromptController classes or instances to register on startup.

skill_controllersSequence[type[Any]]

Optional sequence of SkillController classes or instances to register on startup.

infer_http_method_annotationsbool

Automatically infer default MCP ToolAnnotations hints (readOnlyHint, destructiveHint, idempotentHint) from the route handler's HTTP method when not explicitly overridden.

max_tool_description_lengthint | None

Optional maximum character length for tool descriptions enforced during tool-spec validation.

max_param_description_lengthint | None

Optional maximum character length for input parameter descriptions enforced during tool-spec validation.

max_output_field_description_lengthint | None

Optional maximum character length for output schema property descriptions enforced during tool-spec validation.

task_configMCPTaskConfig | None

Return the normalized task configuration, if task support is enabled.

MCPOptKeys

Configurable names for the handler.opt keys read by the plugin.

Downstream apps can rename any key to avoid collisions with other plugins or app-specific conventions. All fields default to mcp_<purpose> and the pattern mirrors litestar.security.jwt.auth.JWTAuth.exclude_opt_key.

Parameters:

Name Type Description Default
tool str

Opt key that marks a route handler as an MCP tool (handler.opt[tool] = "<tool-name>", or True to use the handler function name).

'mcp_tool'
resource str

Opt key that marks a route handler as an MCP resource.

'mcp_resource'
resource_uri str

Opt key that carries a concrete resource URI override.

'mcp_resource_uri'
resource_mime_type str

Opt key that carries the resource MIME type for list responses and binary resources/read fallbacks.

'mcp_resource_mime_type'
resource_template str

Opt key that carries an RFC 6570 Level 1 URI template for the resource.

'mcp_resource_template'
required_client_capabilities str

Opt key declaring standard client capabilities required before a tool may be invoked.

'mcp_required_client_capabilities'
task_input_before_start str

Opt key selecting a synchronous MRTR input round before task creation.

'mcp_task_input_before_start'
prompt str

Opt key that marks a route handler as an MCP prompt (handler.opt[prompt] = "<prompt-name>").

'mcp_prompt'
description str

Opt key overriding the tool description (handler.opt[description] = "LLM prose").

'mcp_description'
resource_description str

Opt key overriding the resource description, kept distinct from description for dual-role handlers.

'mcp_resource_description'
prompt_description str

Opt key overriding the prompt description.

'mcp_prompt_description'
prompt_title str

Opt key overriding the prompt title.

'mcp_prompt_title'
prompt_arguments str

Opt key overriding the prompt argument list (list[dict] matching the decorator's arguments= param).

'mcp_prompt_arguments'
prompt_icons str

Opt key overriding the prompt icons list (list[dict] matching the decorator's icons= param).

'mcp_prompt_icons'
agent_instructions str

Opt key for the ## Instructions section.

'mcp_agent_instructions'
when_to_use str

Opt key for the ## When to use section.

'mcp_when_to_use'
returns str

Opt key for the ## Returns section.

'mcp_returns'
annotations str

Opt key carrying MCP ToolAnnotations mapping.

'mcp_annotations'
read_only str

Opt key shorthand setting annotations.readOnlyHint.

'mcp_read_only'
task_support str

Opt key declaring MCP Tasks support mode (optional, required, forbidden, or soft aliases).

'mcp_task_support'
task str

Short alias opt key for task_support.

'mcp_task'
queue str

Opt key overriding the target litestar-queues queue name for task-augmented tool execution (or False / "in_process" to force in-process execution).

'mcp_queue'

Attributes:

Name Type Description
toolstr

Opt key that marks a route handler as an MCP tool (handler.opt[tool] = "<tool-name>", or True to use the handler function name).

resourcestr

Opt key that marks a route handler as an MCP resource.

resource_uristr

Opt key that carries a concrete resource URI override.

resource_mime_typestr

Opt key that carries the resource MIME type for list responses and binary resources/read fallbacks.

resource_templatestr

Opt key that carries an RFC 6570 Level 1 URI template for the resource.

required_client_capabilitiesstr

Opt key declaring standard client capabilities required before a tool may be invoked.

task_input_before_startstr

Opt key selecting a synchronous MRTR input round before task creation.

promptstr

Opt key that marks a route handler as an MCP prompt (handler.opt[prompt] = "<prompt-name>").

descriptionstr

Opt key overriding the tool description (handler.opt[description] = "LLM prose").

resource_descriptionstr

Opt key overriding the resource description, kept distinct from description for dual-role handlers.

prompt_descriptionstr

Opt key overriding the prompt description.

prompt_titlestr

Opt key overriding the prompt title.

prompt_argumentsstr

Opt key overriding the prompt argument list (list[dict] matching the decorator's arguments= param).

prompt_iconsstr

Opt key overriding the prompt icons list (list[dict] matching the decorator's icons= param).

agent_instructionsstr

Opt key for the ## Instructions section.

when_to_usestr

Opt key for the ## When to use section.

returnsstr

Opt key for the ## Returns section.

annotationsstr

Opt key carrying MCP ToolAnnotations mapping.

read_onlystr

Opt key shorthand setting annotations.readOnlyHint.

task_supportstr

Opt key declaring MCP Tasks support mode (optional, required, forbidden, or soft aliases).

taskstr

Short alias opt key for task_support.

queuestr

Opt key overriding the target litestar-queues queue name for task-augmented tool execution (or False / "in_process" to force in-process execution).

for_field

for_field(field_name, kind)

Return the opt key for (field_name, kind).

The description field has kind-specific keys (description for tools, resource_description for resources, prompt_description for prompts) so a handler exposing multiple MCP roles on the same route can carry distinct override prose. All other fields are kind-agnostic.

MCPTaskConfig

Configuration for the opt-in MCP Tasks extension.

Parameters:

Name Type Description Default
store Store | None

Litestar Store persisting task records; defaults to an in-memory store.

None
default_ttl_ms int

TTL in milliseconds applied when a client does not request one.

300000
max_ttl_ms int

Upper bound in milliseconds for client-requested TTLs.

3600000
poll_interval_ms int

Poll interval in milliseconds advertised on task records.

1000
status_callback Callable[[Any], Awaitable[None]] | None

Optional coroutine invoked with every task status transition.

None
executor MCPTaskExecutor | None

Optional MCPTaskExecutor that runs task-augmented tool calls outside the creating request (None auto-wires QueueTaskExecutor when QueuePlugin is registered, or pass "in_process" / False to force in-process background tasks).

None

Attributes:

Name Type Description
storeStore | None

Litestar Store persisting task records; defaults to an in-memory store.

default_ttl_msint

TTL in milliseconds applied when a client does not request one.

max_ttl_msint

Upper bound in milliseconds for client-requested TTLs.

poll_interval_msint

Poll interval in milliseconds advertised on task records.

status_callbackCallable[[Any], Awaitable[None]] | None

Optional coroutine invoked with every task status transition.

executorMCPTaskExecutor | Literal['in_process'] | bool | None

Optional MCPTaskExecutor that runs task-augmented tool calls outside the creating request (None auto-wires QueueTaskExecutor when QueuePlugin is registered, or pass "in_process" / False to force in-process background tasks).

MCPSkillsConfig

Configuration for the opt-in Skills over MCP extension.

Parameters:

Name Type Description Default
paths Sequence[Path]

Directories whose immediate child folders containing a SKILL.md file are served as MCP skills (entries are normalized with pathlib.Path; optional when sources is non-empty).

()
directory_read bool

Whether to advertise and serve resources/directory/read.

True
max_files_per_skill int

Maximum files, including SKILL.md, one filesystem skill may contain before it is rejected at startup.

512
max_bytes_per_skill int

Maximum total byte size of one filesystem skill's files before it is rejected at startup.

16777216
sources Sequence[SkillSource]

Async, request-aware SkillSource instances composed after any paths source.

()

Attributes:

Name Type Description
pathsSequence[Path]

Directories whose immediate child folders containing a SKILL.md file are served as MCP skills (entries are normalized with pathlib.Path; optional when sources is non-empty).

directory_readbool

Whether to advertise and serve resources/directory/read.

max_files_per_skillint

Maximum files, including SKILL.md, one filesystem skill may contain before it is rejected at startup.

max_bytes_per_skillint

Maximum total byte size of one filesystem skill's files before it is rejected at startup.

sourcesSequence[SkillSource]

Async, request-aware SkillSource instances composed after any paths source.


Tool-Call Lifecycle Hooks

BeforeToolCallHook

Bases: Protocol

Callback invoked before an MCP tools/call dispatch.

AfterToolCallHook

Bases: Protocol

Callback invoked after an MCP tools/call dispatch.


Streamable HTTP Transport Controller

MCPController

Bases: Controller

MCP JSON-RPC Streamable HTTP controller.

terminate_session

terminate_session(request, config)

Acknowledge stateless Streamable HTTP session termination.

handle_jsonrpc

handle_jsonrpc(
    request,
    config,
    discovered_tools,
    discovered_resources,
    discovered_prompts,
    registry,
    task_store=None,
    skill_catalog=None,
)

Validate and dispatch one independent MCP request.