-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
MCP Server Part 3: Dash App Resources
#3712
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
2
commits into
feature/mcp-callback-adapters
Choose a base branch
from
feature/mcp-resources
base: feature/mcp-callback-adapters
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
2 commits
Select commit
Hold shift + click to select a range
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,52 @@ | ||
| """MCP resource listing and read handling. | ||
|
|
||
| Each resource module exports: | ||
| - ``URI`` — the URI prefix this module handles | ||
| - ``get_resource() -> Resource | None`` | ||
| - ``get_template() -> ResourceTemplate | None`` | ||
| - ``read_resource(uri) -> ReadResourceResult`` | ||
|
|
||
| Dispatch is by prefix match: more specific prefixes must come first. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from mcp.types import ( | ||
| ListResourcesResult, | ||
| ListResourceTemplatesResult, | ||
| ReadResourceResult, | ||
| ) | ||
|
|
||
| from . import ( | ||
| resource_clientside_callbacks as _clientside, | ||
| resource_components as _components, | ||
| resource_layout as _layout, | ||
| resource_page_layout as _page_layout, | ||
| resource_pages as _pages, | ||
| ) | ||
|
|
||
| _RESOURCE_MODULES = [_layout, _components, _pages, _clientside, _page_layout] | ||
|
|
||
|
|
||
| def list_resources() -> ListResourcesResult: | ||
| """Build the MCP resources/list response.""" | ||
| resources = [ | ||
| r for mod in _RESOURCE_MODULES for r in [mod.get_resource()] if r is not None | ||
| ] | ||
| return ListResourcesResult(resources=resources) | ||
|
|
||
|
|
||
| def list_resource_templates() -> ListResourceTemplatesResult: | ||
| """Build the MCP resources/templates/list response.""" | ||
| templates = [ | ||
| t for mod in _RESOURCE_MODULES for t in [mod.get_template()] if t is not None | ||
| ] | ||
| return ListResourceTemplatesResult(resourceTemplates=templates) | ||
|
|
||
|
|
||
| def read_resource(uri: str) -> ReadResourceResult: | ||
| """Dispatch a resources/read request by URI prefix match.""" | ||
| for mod in _RESOURCE_MODULES: | ||
| if uri.startswith(mod.URI): | ||
| return mod.read_resource(uri) | ||
| raise ValueError(f"Unknown resource URI: {uri}") |
95 changes: 95 additions & 0 deletions
95
dash/mcp/primitives/resources/resource_clientside_callbacks.py
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,95 @@ | ||
| """Clientside callbacks resource.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from typing import Any | ||
|
|
||
| from mcp.types import ( | ||
| ReadResourceResult, | ||
| Resource, | ||
| ResourceTemplate, | ||
| TextResourceContents, | ||
| ) | ||
|
|
||
| from dash import get_app | ||
| from dash._utils import clean_property_name, split_callback_id | ||
|
|
||
| URI = "dash://clientside-callbacks" | ||
|
|
||
|
|
||
| def get_resource() -> Resource | None: | ||
| if not _get_clientside_callbacks(): | ||
| return None | ||
| return Resource( | ||
| uri=URI, | ||
| name="dash_clientside_callbacks", | ||
| description=( | ||
| "Actions the user can take manually in the browser " | ||
| "to affect clientside state. Inputs describe the " | ||
| "components that can be changed to trigger an effect. " | ||
| "Outputs describe the components that will change " | ||
| "in response." | ||
| ), | ||
| mimeType="application/json", | ||
| ) | ||
|
|
||
|
|
||
| def get_template() -> ResourceTemplate | None: | ||
| return None | ||
|
|
||
|
|
||
| def read_resource(uri: str = "") -> ReadResourceResult: | ||
| data = { | ||
| "description": ( | ||
| "These are actions that the user can take manually in the " | ||
| "browser to affect the clientside state. Inputs describe " | ||
| "the components that can be changed to trigger an effect. " | ||
| "Outputs describe the components that will change in " | ||
| "response to the effect." | ||
| ), | ||
| "callbacks": _get_clientside_callbacks(), | ||
| } | ||
| return ReadResourceResult( | ||
| contents=[ | ||
| TextResourceContents( | ||
| uri=URI, | ||
| mimeType="application/json", | ||
| text=json.dumps(data, default=str), | ||
| ) | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| def _get_clientside_callbacks() -> list[dict[str, Any]]: | ||
| """Get input/output mappings for clientside callbacks.""" | ||
| app = get_app() | ||
| callbacks = [] | ||
| callback_map = getattr(app, "callback_map", {}) | ||
|
|
||
| for output_id, callback_info in callback_map.items(): | ||
| if "callback" in callback_info: | ||
| continue | ||
| normalize_deps = lambda deps: [ | ||
| { | ||
| "component_id": str(d.get("id", "unknown")), | ||
| "property": d.get("property", "unknown"), | ||
| } | ||
| for d in deps | ||
| ] | ||
| parsed = split_callback_id(output_id) | ||
| if isinstance(parsed, dict): | ||
| parsed = [parsed] | ||
| outputs = [ | ||
| {"component_id": p["id"], "property": clean_property_name(p["property"])} | ||
| for p in parsed | ||
| ] | ||
| callbacks.append( | ||
| { | ||
| "outputs": outputs, | ||
| "inputs": normalize_deps(callback_info.get("inputs", [])), | ||
| "state": normalize_deps(callback_info.get("state", [])), | ||
| } | ||
| ) | ||
|
|
||
| return callbacks | ||
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,59 @@ | ||
| """Component list resource.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
|
|
||
| from mcp.types import ( | ||
| ReadResourceResult, | ||
| Resource, | ||
| ResourceTemplate, | ||
| TextResourceContents, | ||
| ) | ||
|
|
||
| from dash import get_app | ||
| from dash._layout_utils import traverse | ||
|
|
||
| URI = "dash://components" | ||
|
|
||
|
|
||
| def get_resource() -> Resource | None: | ||
| return Resource( | ||
| uri=URI, | ||
| name="dash_components", | ||
| description=( | ||
| "All components with IDs in the app layout. " | ||
| "Use get_dash_component with any of these IDs " | ||
| "to inspect their properties and values. " | ||
| "See dash://layout for the tree structure showing " | ||
| "how these components are nested in the page." | ||
| ), | ||
| mimeType="application/json", | ||
| ) | ||
|
|
||
|
|
||
| def get_template() -> ResourceTemplate | None: | ||
| return None | ||
|
|
||
|
|
||
| def read_resource(uri: str = "") -> ReadResourceResult: | ||
| app = get_app() | ||
| layout = app.get_layout() | ||
| components = sorted( | ||
| [ | ||
| {"id": str(comp.id), "type": getattr(comp, "_type", type(comp).__name__)} | ||
| for comp, _ in traverse(layout) | ||
| if getattr(comp, "id", None) is not None | ||
| ], | ||
| key=lambda c: c["id"], | ||
| ) | ||
|
|
||
| return ReadResourceResult( | ||
| contents=[ | ||
| TextResourceContents( | ||
| uri=URI, | ||
| mimeType="application/json", | ||
| text=json.dumps(components), | ||
| ) | ||
| ] | ||
| ) |
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,44 @@ | ||
| """Layout tree resource for the whole app.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from mcp.types import ( | ||
| ReadResourceResult, | ||
| Resource, | ||
| ResourceTemplate, | ||
| TextResourceContents, | ||
| ) | ||
|
|
||
| from dash import get_app | ||
| from dash._utils import to_json | ||
|
|
||
| URI = "dash://layout" | ||
|
|
||
|
|
||
| def get_resource() -> Resource | None: | ||
| return Resource( | ||
| uri=URI, | ||
| name="dash_app_layout", | ||
| description=( | ||
| "Full component tree of the Dash app. " | ||
| "See dash://components for a compact list of component IDs." | ||
| ), | ||
| mimeType="application/json", | ||
| ) | ||
|
|
||
|
|
||
| def get_template() -> ResourceTemplate | None: | ||
| return None | ||
|
|
||
|
|
||
| def read_resource(uri: str = "") -> ReadResourceResult: | ||
| app = get_app() | ||
| return ReadResourceResult( | ||
| contents=[ | ||
| TextResourceContents( | ||
| uri=URI, | ||
| mimeType="application/json", | ||
| text=to_json(app.get_layout()), | ||
| ) | ||
| ] | ||
| ) |
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,77 @@ | ||
| """Per-page layout resource template for multi-page apps.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from mcp.types import ( | ||
| ReadResourceResult, | ||
| Resource, | ||
| ResourceTemplate, | ||
| TextResourceContents, | ||
| ) | ||
|
|
||
| from dash._utils import to_json | ||
|
|
||
| URI = "dash://page-layout/" | ||
| _URI_TEMPLATE = "dash://page-layout/{path}" | ||
|
|
||
|
|
||
| def get_resource() -> Resource | None: | ||
| return None | ||
|
|
||
|
|
||
| def get_template() -> ResourceTemplate | None: | ||
| if not _has_pages(): | ||
| return None | ||
| return ResourceTemplate( | ||
| uriTemplate=_URI_TEMPLATE, | ||
| name="dash_page_layout", | ||
| description="Component tree for a specific page in the app.", | ||
| mimeType="application/json", | ||
| ) | ||
|
|
||
|
|
||
| def read_resource(uri: str) -> ReadResourceResult: | ||
| path = uri[len(URI) :] | ||
| if not path.startswith("/"): | ||
| path = "/" + path | ||
|
|
||
| try: | ||
| from dash._pages import PAGE_REGISTRY | ||
| except ImportError: | ||
| raise ValueError("Dash Pages is not available.") | ||
|
Comment on lines
+38
to
+41
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why would this import be not available? |
||
|
|
||
| page_layout = None | ||
| for _module, page in PAGE_REGISTRY.items(): | ||
| if page.get("path") == path: | ||
| page_layout = page.get("layout") | ||
| break | ||
|
|
||
| if page_layout is None: | ||
| raise ValueError(f"Page not found: {path}") | ||
|
|
||
| if callable(page_layout): | ||
| page_layout = page_layout() | ||
|
|
||
| if isinstance(page_layout, (list, tuple)): | ||
| from dash import html | ||
|
|
||
| page_layout = html.Div(list(page_layout)) | ||
|
|
||
| return ReadResourceResult( | ||
| contents=[ | ||
| TextResourceContents( | ||
| uri=uri, | ||
| mimeType="application/json", | ||
| text=to_json(page_layout), | ||
| ) | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| def _has_pages() -> bool: | ||
| try: | ||
| from dash._pages import PAGE_REGISTRY | ||
|
|
||
| return bool(PAGE_REGISTRY) | ||
| except ImportError: | ||
| return False | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is this necessary if it only returns None? Seems like the modules are being used as a class, maybe refactor to a base class instead.