-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
MCP Server Part 7: get_dash_component tool and callback tool execution
#3749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
KoolADE85
wants to merge
6
commits into
mcp
Choose a base branch
from
feature/mcp-get-dash-component-tool
base: mcp
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
759ed5b
Add get_dash_component tool and callback tool dispatch pipeline
KoolADE85 bb187ce
Refactor tools to use a base class (just as resources do)
KoolADE85 e175b28
lint
KoolADE85 2a7bb84
Refactor unit tests to conform to existing test patterns
KoolADE85 4c0fd0f
Implement a mapping of "id+prop" to callbacks that are outputs/inputs…
KoolADE85 d25123b
Code review feedback
KoolADE85 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| """MCP tool listing and call handling.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from mcp.types import CallToolResult, ListToolsResult | ||
|
|
||
| from dash.mcp.types import ToolNotFoundError | ||
|
|
||
| from .base import MCPToolProvider | ||
| from .tool_get_dash_component import GetDashComponentTool | ||
| from .tools_callbacks import CallbackTools | ||
|
|
||
| _TOOL_PROVIDERS: list[type[MCPToolProvider]] = [ | ||
| CallbackTools, | ||
| GetDashComponentTool, | ||
| ] | ||
|
|
||
|
|
||
| def list_tools() -> ListToolsResult: | ||
| """Build the MCP tools/list response.""" | ||
| tools = [] | ||
| for provider in _TOOL_PROVIDERS: | ||
| tools.extend(provider.list_tools()) | ||
| return ListToolsResult(tools=tools) | ||
|
|
||
|
|
||
| def call_tool(tool_name: str, arguments: dict[str, Any]) -> CallToolResult: | ||
| """Route a tools/call request by tool name.""" | ||
| for provider in _TOOL_PROVIDERS: | ||
| if tool_name in provider.get_tool_names(): | ||
| return provider.call_tool(tool_name, arguments) | ||
| raise ToolNotFoundError( | ||
| f"Tool not found: {tool_name}." | ||
| " The app's callbacks may have changed." | ||
| " Please call tools/list to refresh your tool list." | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| """Base class for MCP tool providers.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from mcp.types import CallToolResult, Tool | ||
|
|
||
|
|
||
| class MCPToolProvider: | ||
| """A provider of one or more MCP tools. | ||
|
|
||
| Subclasses implement ``list_tools`` to return the tools they provide, | ||
| ``get_tool_names`` to advertise those names for routing, and | ||
| ``call_tool`` to execute a tool by name. | ||
| """ | ||
|
|
||
| @classmethod | ||
| def get_tool_names(cls) -> set[str]: | ||
| raise NotImplementedError | ||
|
|
||
| @classmethod | ||
| def list_tools(cls) -> list[Tool]: | ||
| raise NotImplementedError | ||
|
|
||
| @classmethod | ||
| def call_tool(cls, tool_name: str, arguments: dict[str, Any]) -> CallToolResult: | ||
| raise NotImplementedError |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| """Built-in tool: get_dash_component.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from typing import Any | ||
|
|
||
| from mcp.types import CallToolResult, TextContent, Tool | ||
| from pydantic import Field, TypeAdapter | ||
| from typing_extensions import Annotated, NotRequired, TypedDict | ||
|
|
||
| from dash import get_app | ||
| from dash._layout_utils import find_component | ||
| from dash.mcp.types import ComponentPropertyInfo, ComponentQueryResult | ||
|
|
||
| from .base import MCPToolProvider | ||
|
|
||
|
|
||
| class _ComponentQueryInput(TypedDict): | ||
| component_id: Annotated[str, Field(description="The component ID to query")] | ||
| property: NotRequired[ | ||
| Annotated[ | ||
| str, | ||
| Field( | ||
| description="The property name to read (e.g. 'options', 'value'). Omit to list all defined properties." | ||
| ), | ||
| ] | ||
| ] | ||
|
|
||
|
|
||
| _INPUT_SCHEMA = TypeAdapter(_ComponentQueryInput).json_schema() | ||
| _OUTPUT_SCHEMA = TypeAdapter(ComponentQueryResult).json_schema() | ||
|
|
||
| NAME = "get_dash_component" | ||
|
|
||
|
|
||
| class GetDashComponentTool(MCPToolProvider): | ||
| """Inspects a component's properties and its tool relationships.""" | ||
|
|
||
| @classmethod | ||
| def get_tool_names(cls) -> set[str]: | ||
| return {NAME} | ||
|
|
||
| @classmethod | ||
| def list_tools(cls) -> list[Tool]: | ||
| return [ | ||
| Tool( | ||
| name=NAME, | ||
| description=( | ||
| "Get a component's properties, values, and tool relationships. " | ||
| "If property is omitted, returns all defined properties. " | ||
| "If property is specified, returns only that property. " | ||
| "See the dash://components resource for available component IDs." | ||
| ), | ||
| inputSchema=_INPUT_SCHEMA, | ||
| outputSchema=_OUTPUT_SCHEMA, | ||
| ) | ||
| ] | ||
|
|
||
| @classmethod | ||
| def call_tool(cls, tool_name: str, arguments: dict[str, Any]) -> CallToolResult: | ||
| comp_id = arguments.get("component_id", "") | ||
| if not comp_id: | ||
| return CallToolResult( | ||
| content=[TextContent(type="text", text="component_id is required")], | ||
| isError=True, | ||
| ) | ||
|
|
||
| prop_filter = arguments.get("property", "") | ||
| component = find_component(comp_id) | ||
| callback_map = get_app().mcp_callback_map | ||
|
|
||
| if component is None: | ||
| rendering_tools = [ | ||
| cb.tool_name | ||
| for cb in callback_map | ||
| if any(out["component_id"] == comp_id for out in cb.outputs) | ||
| ] | ||
| msg = f"Component '{comp_id}' not found in static layout." | ||
| if rendering_tools: | ||
| msg += ( | ||
| f" However, the following tools would modify it: {rendering_tools}." | ||
| ) | ||
| msg += " Use the dash://components resource to see statically available component IDs." | ||
| return CallToolResult( | ||
| content=[TextContent(type="text", text=msg)], | ||
| isError=True, | ||
| ) | ||
|
|
||
| properties: dict[str, ComponentPropertyInfo] = {} | ||
| for prop_name in getattr(component, "_prop_names", []): | ||
| if prop_filter and prop_name != prop_filter: | ||
| continue | ||
|
|
||
| id_and_prop = f"{comp_id}.{prop_name}" | ||
| value = callback_map.get_initial_value(id_and_prop) | ||
| if value is None: | ||
| value = getattr(component, prop_name, None) | ||
| if value is None: | ||
| continue | ||
|
|
||
| modified_by = [ | ||
| cb.tool_name for cb in callback_map.outputs_by_prop.get(id_and_prop, []) | ||
| ] | ||
| input_to = [ | ||
| cb.tool_name for cb in callback_map.inputs_by_prop.get(id_and_prop, []) | ||
| ] | ||
|
|
||
| properties[prop_name] = ComponentPropertyInfo( | ||
| initial_value=value, | ||
| modified_by_tool=modified_by, | ||
| input_to_tool=input_to, | ||
| ) | ||
|
|
||
| labels = callback_map.component_label_map.get(comp_id, []) | ||
|
|
||
| structured: ComponentQueryResult = ComponentQueryResult( | ||
| component_id=comp_id, | ||
| component_type=type(component).__name__, | ||
| label=labels if labels else None, | ||
| properties=properties, | ||
| ) | ||
|
|
||
| return CallToolResult( | ||
| content=[ | ||
| TextContent(type="text", text=json.dumps(structured, default=str)) | ||
| ], | ||
| structuredContent=structured, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| """Dynamic callback tools for MCP. | ||
|
|
||
| Exposes every server-callable callback as an MCP tool. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from mcp.types import CallToolResult, TextContent, Tool | ||
|
|
||
| from dash import get_app | ||
| from dash.mcp.types import CallbackExecutionError, ToolNotFoundError | ||
|
|
||
| from .base import MCPToolProvider | ||
| from .callback_utils import run_callback | ||
| from .results import format_callback_response | ||
|
|
||
|
|
||
| class CallbackTools(MCPToolProvider): | ||
| """Exposes every server-callable callback as an MCP tool.""" | ||
|
|
||
| @classmethod | ||
| def get_tool_names(cls) -> set[str]: | ||
| return get_app().mcp_callback_map.tool_names | ||
|
|
||
| @classmethod | ||
| def list_tools(cls) -> list[Tool]: | ||
| """Return one Tool per server-callable callback.""" | ||
| return get_app().mcp_callback_map.as_mcp_tools() | ||
|
|
||
| @classmethod | ||
| def call_tool(cls, tool_name: str, arguments: dict[str, Any]) -> CallToolResult: | ||
| """Execute a callback tool by name.""" | ||
| callback_map = get_app().mcp_callback_map | ||
| cb = callback_map.find_by_tool_name(tool_name) | ||
| if cb is None: | ||
| raise ToolNotFoundError( | ||
| f"Tool not found: {tool_name}." | ||
| " The app's callbacks may have changed." | ||
| " Please call tools/list to refresh your tool list." | ||
| ) | ||
|
|
||
| try: | ||
| callback_response = run_callback(cb, arguments) | ||
| except CallbackExecutionError as e: | ||
| return CallToolResult( | ||
| content=[TextContent(type="text", text=str(e))], | ||
| isError=True, | ||
| ) | ||
| return format_callback_response(callback_response, cb) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.