-
Notifications
You must be signed in to change notification settings - Fork 2
Nexus transport for workflow callers #1
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
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
016c50b
Workflow caller
dandavison 5e43c16
Rename and add docstring
dandavison a0d71d5
README fixes
dandavison ac63af2
Export WorkflowNexusTransport at top-level
dandavison 4eca5c9
Comment on disabling of sandbox
dandavison 1654319
Update README
dandavison 4732489
Rename transport
dandavison 861b563
Document that JSONRPCNotification are skipped
dandavison ca16e6e
Add anyio to dependencies
dandavison c6c5964
Update TODO
dandavison 361b7cf
Use pydantic data converter everywhere
dandavison 5244fb7
README edits and .gitignore
dandavison d59c500
Use temporalio main
dandavison 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,2 @@ | ||
| __pycache__/ | ||
| *.egg-info/ |
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
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 |
|---|---|---|
|
|
@@ -12,7 +12,6 @@ | |
|
|
||
| class ToolListInput(BaseModel): | ||
| endpoint: str | ||
| pass | ||
|
|
||
|
|
||
| class ToolCallInput(BaseModel): | ||
|
|
||
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,152 @@ | ||
| import asyncio | ||
| from contextlib import asynccontextmanager | ||
| from typing import Any, AsyncGenerator | ||
|
|
||
| import anyio | ||
| import mcp.types as types | ||
| import pydantic | ||
| from mcp.shared.message import SessionMessage | ||
| from temporalio import workflow | ||
|
|
||
| from .service import MCPService | ||
|
|
||
|
|
||
| class WorkflowTransport: | ||
| """ | ||
| An MCP Transport for use in Temporal workflows. | ||
|
|
||
| This class provides a transport that proxies MCP requests from a Temporal Workflow to a Temporal | ||
| Nexus service. It can be used to make MCP calls via `mcp.ClientSession` from Temporal workflow | ||
| code. | ||
|
|
||
| Example: | ||
| ```python async with WorkflowNexusTransport("my-endpoint") as (read_stream, write_stream): | ||
| async with ClientSession(read_stream, write_stream) as session: | ||
| await session.initialize() await session.list_tools() await | ||
| session.call_tool("my-service/my-operation", {"arg": "value"}) | ||
| ``` | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| endpoint: str, | ||
| ): | ||
| self.endpoint = endpoint | ||
|
|
||
| @asynccontextmanager | ||
| async def connect( | ||
| self, | ||
| ) -> AsyncGenerator[ | ||
| tuple[ | ||
| anyio.streams.memory.MemoryObjectReceiveStream[SessionMessage], | ||
| anyio.streams.memory.MemoryObjectSendStream[SessionMessage], | ||
| ], | ||
| None, | ||
| ]: | ||
| client_write, transport_read = anyio.create_memory_object_stream(0) # type: ignore[var-annotated] | ||
| transport_write, client_read = anyio.create_memory_object_stream(0) # type: ignore[var-annotated] | ||
|
|
||
| async def message_router() -> None: | ||
| try: | ||
| async for session_message in transport_read: | ||
| request = session_message.message.root | ||
| if not isinstance(request, types.JSONRPCRequest): | ||
| # Ignore e.g. types.JSONRPCNotification | ||
| continue | ||
| result: types.Result | types.ErrorData | ||
| try: | ||
| match request: | ||
| case types.JSONRPCRequest(method="initialize"): | ||
| result = self._handle_initialize( | ||
| types.InitializeRequestParams.model_validate(request.params) | ||
| ) | ||
| case types.JSONRPCRequest(method="tools/list"): | ||
| result = await self._handle_list_tools() | ||
| case types.JSONRPCRequest(method="tools/call"): | ||
| result = await self._handle_call_tool( | ||
| types.CallToolRequestParams.model_validate(request.params) | ||
| ) | ||
| case _: | ||
| result = types.ErrorData( | ||
| code=types.METHOD_NOT_FOUND, message=f"Unknown method: {request.method}" | ||
| ) | ||
| except pydantic.ValidationError as e: | ||
| result = types.ErrorData(code=types.INVALID_PARAMS, message=f"Invalid request: {e}") | ||
|
|
||
| match result: | ||
| case types.Result(): | ||
| response = self._json_rpc_result_response(request, result) | ||
| case types.ErrorData(): | ||
| response = self._json_rpc_error_response(request, result) | ||
|
|
||
| await transport_write.send(SessionMessage(types.JSONRPCMessage(root=response))) | ||
|
|
||
| except anyio.ClosedResourceError: | ||
| pass | ||
| finally: | ||
| await transport_write.aclose() | ||
|
|
||
| router_task = asyncio.create_task(message_router()) | ||
|
|
||
| try: | ||
| yield client_read, client_write | ||
| finally: | ||
| await client_write.aclose() | ||
| router_task.cancel() | ||
| try: | ||
| await router_task | ||
| except asyncio.CancelledError: | ||
| pass | ||
| await transport_read.aclose() | ||
|
|
||
| def _handle_initialize(self, params: types.InitializeRequestParams) -> types.InitializeResult: | ||
| # TODO: MCPService should implement this | ||
| return types.InitializeResult( | ||
| protocolVersion="2024-11-05", | ||
| capabilities=types.ServerCapabilities(tools=types.ToolsCapability()), | ||
| serverInfo=types.Implementation( | ||
| name="nexus-mcp-transport", | ||
| version="0.1.0", | ||
| ), | ||
| ) | ||
|
|
||
| async def _handle_list_tools(self) -> types.ListToolsResult: | ||
| nexus_client = workflow.create_nexus_client( | ||
| endpoint=self.endpoint, | ||
| service=MCPService, | ||
| ) | ||
| tools = await nexus_client.execute_operation(MCPService.list_tools, None) | ||
| return types.ListToolsResult(tools=tools) | ||
|
|
||
| async def _handle_call_tool(self, params: types.CallToolRequestParams) -> types.CallToolResult: | ||
| service, _, operation = params.name.partition("/") | ||
| nexus_client = workflow.create_nexus_client( | ||
| endpoint=self.endpoint, | ||
| service=service, | ||
| ) | ||
| result: Any = await nexus_client.execute_operation( | ||
| operation, | ||
| params.arguments or {}, | ||
| ) | ||
| if isinstance(result, dict): | ||
| return types.CallToolResult(content=[], structuredContent=result) | ||
| else: | ||
| return types.CallToolResult(content=[types.TextContent(type="text", text=str(result))]) | ||
|
|
||
| def _json_rpc_error_response(self, request: types.JSONRPCRequest, error: types.ErrorData) -> types.JSONRPCResponse: | ||
| return types.JSONRPCResponse.model_validate( | ||
| { | ||
| "jsonrpc": "2.0", | ||
| "id": request.id, | ||
| "error": error.model_dump(), | ||
| } | ||
| ) | ||
|
|
||
| def _json_rpc_result_response(self, request: types.JSONRPCRequest, result: types.Result) -> types.JSONRPCResponse: | ||
| return types.JSONRPCResponse.model_validate( | ||
| { | ||
| "jsonrpc": "2.0", | ||
| "id": request.id, | ||
| "result": result.model_dump(), | ||
| } | ||
| ) |
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
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.
Ah, I forgot to add that on the handler side, want to do that before merging? Otherwise, I can take that on.
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.
Sure -- I've added it to all the client connections in the README and tests.