|
| 1 | +# Copyright 2025-2026 Dimensional Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import asyncio |
| 17 | +import json |
| 18 | +from typing import TYPE_CHECKING, Any |
| 19 | +import uuid |
| 20 | + |
| 21 | +from dimos.core import Module, rpc |
| 22 | +from dimos.protocol.skill.coordinator import SkillCoordinator, SkillStateEnum |
| 23 | + |
| 24 | +if TYPE_CHECKING: |
| 25 | + from dimos.protocol.skill.coordinator import SkillState |
| 26 | + |
| 27 | + |
| 28 | +class MCPModule(Module): |
| 29 | + def __init__(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def] |
| 30 | + super().__init__(*args, **kwargs) |
| 31 | + self.coordinator = SkillCoordinator() |
| 32 | + self._server: asyncio.AbstractServer | None = None |
| 33 | + self._server_future: object | None = None |
| 34 | + |
| 35 | + @rpc |
| 36 | + def start(self) -> None: |
| 37 | + super().start() |
| 38 | + self.coordinator.start() |
| 39 | + self._start_server() |
| 40 | + |
| 41 | + @rpc |
| 42 | + def stop(self) -> None: |
| 43 | + if self._server: |
| 44 | + self._server.close() |
| 45 | + loop = self._loop |
| 46 | + assert loop is not None |
| 47 | + asyncio.run_coroutine_threadsafe(self._server.wait_closed(), loop).result() |
| 48 | + self._server = None |
| 49 | + if self._server_future and hasattr(self._server_future, "cancel"): |
| 50 | + self._server_future.cancel() |
| 51 | + self.coordinator.stop() |
| 52 | + super().stop() |
| 53 | + |
| 54 | + @rpc |
| 55 | + def register_skills(self, container) -> None: # type: ignore[no-untyped-def] |
| 56 | + self.coordinator.register_skills(container) |
| 57 | + |
| 58 | + def _start_server(self, port: int = 9990) -> None: |
| 59 | + async def handle_client(reader, writer) -> None: # type: ignore[no-untyped-def] |
| 60 | + while True: |
| 61 | + if not (data := await reader.readline()): |
| 62 | + break |
| 63 | + response = await self._handle_request(json.loads(data.decode())) |
| 64 | + writer.write(json.dumps(response).encode() + b"\n") |
| 65 | + await writer.drain() |
| 66 | + writer.close() |
| 67 | + |
| 68 | + async def start_server() -> None: |
| 69 | + self._server = await asyncio.start_server(handle_client, "0.0.0.0", port) |
| 70 | + await self._server.serve_forever() |
| 71 | + |
| 72 | + loop = self._loop |
| 73 | + assert loop is not None |
| 74 | + self._server_future = asyncio.run_coroutine_threadsafe(start_server(), loop) |
| 75 | + |
| 76 | + async def _handle_request(self, request: dict[str, Any]) -> dict[str, Any]: |
| 77 | + method = request.get("method", "") |
| 78 | + params = request.get("params", {}) or {} |
| 79 | + req_id = request.get("id") |
| 80 | + if method == "initialize": |
| 81 | + init_result = { |
| 82 | + "protocolVersion": "2024-11-05", |
| 83 | + "capabilities": {"tools": {}}, |
| 84 | + "serverInfo": {"name": "dimensional", "version": "1.0.0"}, |
| 85 | + } |
| 86 | + return {"jsonrpc": "2.0", "id": req_id, "result": init_result} |
| 87 | + if method == "tools/list": |
| 88 | + tools = [ |
| 89 | + { |
| 90 | + "name": c.name, |
| 91 | + "description": c.schema.get("function", {}).get("description", ""), |
| 92 | + "inputSchema": c.schema.get("function", {}).get("parameters", {}), |
| 93 | + } |
| 94 | + for c in self.coordinator.skills().values() |
| 95 | + if not c.hide_skill |
| 96 | + ] |
| 97 | + return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": tools}} |
| 98 | + if method == "tools/call": |
| 99 | + name = params.get("name") |
| 100 | + args = params.get("arguments") or {} |
| 101 | + if not isinstance(name, str): |
| 102 | + return { |
| 103 | + "jsonrpc": "2.0", |
| 104 | + "id": req_id, |
| 105 | + "error": {"code": -32602, "message": "Missing or invalid tool name"}, |
| 106 | + } |
| 107 | + if not isinstance(args, dict): |
| 108 | + args = {} |
| 109 | + call_id = str(uuid.uuid4()) |
| 110 | + self.coordinator.call_skill(call_id, name, args) |
| 111 | + result: SkillState | None = self.coordinator._skill_state.get(call_id) |
| 112 | + try: |
| 113 | + await asyncio.wait_for(self.coordinator.wait_for_updates(), timeout=5.0) |
| 114 | + except asyncio.TimeoutError: |
| 115 | + pass |
| 116 | + if result is None: |
| 117 | + text = "Skill not found" |
| 118 | + elif result.state == SkillStateEnum.completed: |
| 119 | + text = str(result.content()) if result.content() else "Completed" |
| 120 | + elif result.state == SkillStateEnum.error: |
| 121 | + text = f"Error: {result.content()}" |
| 122 | + else: |
| 123 | + text = f"Started ({result.state.name})" |
| 124 | + return { |
| 125 | + "jsonrpc": "2.0", |
| 126 | + "id": req_id, |
| 127 | + "result": {"content": [{"type": "text", "text": text}]}, |
| 128 | + } |
| 129 | + return { |
| 130 | + "jsonrpc": "2.0", |
| 131 | + "id": req_id, |
| 132 | + "error": {"code": -32601, "message": f"Unknown: {method}"}, |
| 133 | + } |
0 commit comments