File size: 15,649 Bytes
a876f68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""

ToolStore as an MCP server.



Exposes all indexed tools (api, mcp, skill) as MCP tools/resources/prompts

so any MCP-compatible host (Claude Desktop, VS Code, etc.) can connect and

use the entire ToolStore catalog.



Implements the full MCP server feature set:

- tools/list, tools/call

- resources/list, resources/read

- prompts/list, prompts/get

- notifications for list changes



Supports stdio transport natively, plus a FastAPI integration for SSE.

"""

from __future__ import annotations

import json
import sys
import threading
from typing import Dict, List, Any, Optional, Callable

from toolstore.schema_converter import (
    toolstore_to_mcp, flatten_mcp_content, bulk_to_openai
)
from toolstore.skill_manager import get_skill_manager


# ---------------------------------------------------------------------------
# ToolStore MCP Server (protocol logic only — transport agnostic)
# ---------------------------------------------------------------------------

class ToolStoreMCPServer:
    """Protocol handler for ToolStore-as-MCP-server.



    This is transport-agnostic. Hook it up to stdio or an SSE endpoint.

    """

    PROTOCOL_VERSION = "2024-11-05"
    SERVER_NAME = "toolstore"
    SERVER_VERSION = "2.0.0"

    def __init__(self, index_manager, config_manager, skill_manager=None):
        self._index = index_manager
        self._config = config_manager
        self._skills = skill_manager or get_skill_manager()
        self._request_id = 0
        self._lock = threading.Lock()
        self._on_send: Optional[Callable[[Dict[str, Any]], None]] = None
        # Track whether capabilities were declared
        self._declared_caps: Dict[str, Any] = {}

    # ------------------------------------------------------------------
    # Transport hook
    # ------------------------------------------------------------------

    def set_send_callback(self, callback: Callable[[Dict[str, Any]], None]) -> None:
        """Register the function used to send messages back to the client."""
        self._on_send = callback

    def handle_message(self, raw: Dict[str, Any]) -> None:
        """Process an incoming JSON-RPC message from the client."""
        method = raw.get("method")
        rid = raw.get("id")
        params = raw.get("params", {})

        # Notification (no id)
        if rid is None:
            self._handle_notification(method, params)
            return

        # Request
        try:
            result = self._dispatch(method, params)
            self._send({"jsonrpc": "2.0", "id": rid, "result": result})
        except Exception as exc:
            self._send({
                "jsonrpc": "2.0", "id": rid,
                "error": {"code": -32603, "message": str(exc)},
            })

    # ------------------------------------------------------------------
    # Dispatch
    # ------------------------------------------------------------------

    def _dispatch(self, method: str, params: Any) -> Any:
        handlers = {
            "initialize": self._handle_initialize,
            "tools/list": self._handle_tools_list,
            "tools/call": self._handle_tools_call,
            "resources/list": self._handle_resources_list,
            "resources/read": self._handle_resources_read,
            "prompts/list": self._handle_prompts_list,
            "prompts/get": self._handle_prompts_get,
        }
        handler = handlers.get(method)
        if handler is None:
            raise RuntimeError(f"Unknown method: {method}")
        return handler(params)

    def _handle_notification(self, method: str, params: Any) -> None:
        if method == "notifications/initialized":
            pass  # client is ready
        # Silently ignore others

    # ------------------------------------------------------------------
    # initialize
    # ------------------------------------------------------------------

    def _handle_initialize(self, params: Dict[str, Any]) -> Dict[str, Any]:
        self._declared_caps = {
            "tools": {"listChanged": True},
            "resources": {"listChanged": False},
            "prompts": {"listChanged": False},
        }
        return {
            "protocolVersion": self.PROTOCOL_VERSION,
            "capabilities": self._declared_caps,
            "serverInfo": {
                "name": self.SERVER_NAME,
                "version": self.SERVER_VERSION,
            },
        }

    # ------------------------------------------------------------------
    # tools/list
    # ------------------------------------------------------------------

    def _handle_tools_list(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """Return all indexed tools in MCP format."""
        tools = []
        all_tools = self._index.index_data.get("tools", {})
        for _name, tool_def in all_tools.items():
            tools.append(toolstore_to_mcp(tool_def))
        # Also include live MCP-scanned tools not yet in index? For now,
        # only indexed tools are exposed.
        return {"tools": tools}

    # ------------------------------------------------------------------
    # tools/call
    # ------------------------------------------------------------------

    def _handle_tools_call(self, params: Dict[str, Any]) -> Dict[str, Any]:
        tool_name = params["name"]
        arguments = params.get("arguments", {})

        tool_def = self._index.get_tool(tool_name)
        if not tool_def:
            return {
                "content": [{"type": "text", "text": f"Tool '{tool_name}' not found"}],
                "isError": True,
            }

        # Dispatch by type
        tool_type = tool_def.get("type", "api")
        try:
            if tool_type == "skill":
                return self._execute_skill(tool_def, arguments)
            elif tool_type == "api":
                return self._execute_api(tool_def, arguments)
            elif tool_type == "mcp":
                return self._execute_mcp(tool_def, arguments)
            else:
                return {
                    "content": [{"type": "text",
                                 "text": f"Unknown tool type: {tool_type}"}],
                    "isError": True,
                }
        except Exception as exc:
            return {
                "content": [{"type": "text", "text": str(exc)}],
                "isError": True,
            }

    def _execute_api(self, tool_def: Dict[str, Any],

                     args: Dict[str, Any]) -> Dict[str, Any]:
        import httpx
        url = tool_def["endpoint"]
        method = tool_def.get("method", "GET").upper()
        # Path param substitution
        final_url = url
        for k, v in args.items():
            if f"{{{k}}}" in final_url:
                final_url = final_url.replace(f"{{{k}}}", str(v))
        request_params = {k: v for k, v in args.items()
                          if f"{{{k}}}" not in url}
        if method == "GET":
            resp = httpx.get(final_url, params=request_params, timeout=30.0)
        else:
            resp = httpx.request(method, final_url, json=request_params,
                                 timeout=30.0)
        try:
            body = json.dumps(resp.json(), indent=2)
        except Exception:
            body = resp.text
        return {"content": [{"type": "text", "text": body}]}

    def _execute_mcp(self, tool_def: Dict[str, Any],

                     args: Dict[str, Any]) -> Dict[str, Any]:
        from toolstore.mcp_client import get_client
        server_name = tool_def.get("mcp_server")
        if not server_name:
            return {"content": [{"type": "text",
                                 "text": "Tool missing mcp_server"}],
                    "isError": True}
        servers = self._config.get_mcp_servers()
        config = servers.get(server_name)
        if not config:
            return {"content": [{"type": "text",
                                 "text": f"MCP server '{server_name}' "
                                         "not configured"}],
                    "isError": True}
        client = get_client(server_name, config)
        result = client.call_tool(tool_def["name"], args)
        return result  # already has 'content' and 'isError'

    def _execute_skill(self, tool_def: Dict[str, Any],

                       args: Dict[str, Any]) -> Dict[str, Any]:
        """Execute a skill tool. Args: load/files/file/run, script?"""
        action = args.get("action", "load")
        skill_name = tool_def["name"]

        # Ensure the skill manager has this skill loaded
        if not self._skills.get_skill(skill_name):
            from toolstore.skill_manager import SkillManager
            dirs = self._config.get_skill_dirs()
            if dirs:
                fresh = SkillManager(dirs)
                fresh.scan()
                self._skills = fresh

        if action == "load":
            body = self._skills.get_skill_body(skill_name)
            if body is None:
                return {"content": [{"type": "text",
                                     "text": f"Skill '{skill_name}' not loaded"}],
                        "isError": True}
            return {"content": [{"type": "text", "text": body}]}

        elif action == "files":
            sd = self._skills.get_skill(skill_name)
            if not sd:
                return {"content": [{"type": "text",
                                     "text": f"Skill '{skill_name}' not found"}],
                        "isError": True}
            flist = [str(f) for f in sd.list_files()]
            return {"content": [{"type": "text",
                                 "text": "\n".join(flist) or "(no extra files)"}]}

        elif action == "file":
            file_path = args.get("file_path", "")
            if not file_path:
                return {"content": [{"type": "text",
                                     "text": "file_path is required for "
                                             "action='file'"}],
                        "isError": True}
            content = self._skills.get_skill_file(skill_name, file_path)
            if content is None:
                return {"content": [{"type": "text",
                                     "text": f"File '{file_path}' not found "
                                             f"in skill '{skill_name}'"}],
                        "isError": True}
            return {"content": [{"type": "text", "text": content}]}

        elif action == "run":
            script = args.get("script", "")
            if not script:
                return {"content": [{"type": "text",
                                     "text": "'script' argument required for action='run'"}],
                        "isError": True}
            output = self._skills.run_skill_script(skill_name, script)
            return {"content": [{"type": "text", "text": output}]}

        else:
            return {"content": [{"type": "text",
                                 "text": f"Unknown action: {action}"}],
                    "isError": True}

    # ------------------------------------------------------------------
    # resources/list
    # ------------------------------------------------------------------

    def _handle_resources_list(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """Expose skill SKILL.md files as resources."""
        resources = []
        for name, sd in self._skills._skills.items():
            resources.append({
                "uri": f"skill://{name}/SKILL.md",
                "name": f"Skill: {name}",
                "description": sd.description,
                "mimeType": "text/markdown",
            })
        return {"resources": resources}

    # ------------------------------------------------------------------
    # resources/read
    # ------------------------------------------------------------------

    def _handle_resources_read(self, params: Dict[str, Any]) -> Dict[str, Any]:
        uri = params["uri"]
        # Parse skill:// URIs
        if uri.startswith("skill://") and uri.endswith("/SKILL.md"):
            name = uri[len("skill://"):-len("/SKILL.md")]
            body = self._skills.get_skill_body(name)
            if body is not None:
                return {
                    "contents": [{
                        "uri": uri,
                        "mimeType": "text/markdown",
                        "text": body,
                    }],
                }
        # Fallback: read raw from any indexed tool's schema
        for tname, tool_def in self._index.index_data.get("tools", {}).items():
            if uri == f"tool://{tname}":
                return {
                    "contents": [{
                        "uri": uri,
                        "mimeType": "application/json",
                        "text": json.dumps(tool_def, indent=2),
                    }],
                }
        raise RuntimeError(f"Resource not found: {uri}")

    # ------------------------------------------------------------------
    # prompts/list
    # ------------------------------------------------------------------

    def _handle_prompts_list(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """Expose each loaded skill's body as an available prompt."""
        prompts = []
        for name, sd in self._skills._skills.items():
            prompts.append({
                "name": name,
                "description": sd.description or f"Skill: {name}",
                "arguments": [],
            })
        return {"prompts": prompts}

    # ------------------------------------------------------------------
    # prompts/get
    # ------------------------------------------------------------------

    def _handle_prompts_get(self, params: Dict[str, Any]) -> Dict[str, Any]:
        name = params["name"]
        body = self._skills.get_skill_body(name)
        if body is None:
            raise RuntimeError(f"Prompt not found: {name}")
        return {
            "description": f"Skill instructions for {name}",
            "messages": [
                {"role": "user", "content": {"type": "text", "text": body}},
            ],
        }

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------

    def _send(self, message: Dict[str, Any]) -> None:
        if self._on_send:
            self._on_send(message)

    # ------------------------------------------------------------------
    # Stdio runner (for standalone mode)
    # ------------------------------------------------------------------

    def run_stdio(self) -> None:
        """Run the server on stdin/stdout (e.g. for Claude Desktop)."""
        self.set_send_callback(
            lambda msg: sys.stdout.write(json.dumps(msg) + "\n")
        )
        # Debug logging to stderr
        print(f"ToolStore MCP Server v{self.SERVER_VERSION} ready",
              file=sys.stderr)
        for line in sys.stdin:
            line = line.strip()
            if not line:
                continue
            try:
                msg = json.loads(line)
            except json.JSONDecodeError:
                continue
            self.handle_message(msg)
            sys.stdout.flush()