mcp-on-demand-tools 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcp_on_demand_tools/__init__.py +9 -0
- mcp_on_demand_tools/recipes/render_template.yaml +58 -0
- mcp_on_demand_tools/server.py +340 -0
- mcp_on_demand_tools-0.1.0.dist-info/METADATA +303 -0
- mcp_on_demand_tools-0.1.0.dist-info/RECORD +8 -0
- mcp_on_demand_tools-0.1.0.dist-info/WHEEL +4 -0
- mcp_on_demand_tools-0.1.0.dist-info/entry_points.txt +2 -0
- mcp_on_demand_tools-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,58 @@
|
|
1
|
+
version: "1.0.0"
|
2
|
+
title: "Simulate Tool Runtime"
|
3
|
+
description: "Renders a prompt template with provided tool context and returns the output payload."
|
4
|
+
instructions: >
|
5
|
+
You are a tool runtime simulator. Your only job is to produce the tool's expected output payload.
|
6
|
+
You do not have access to any other tools or external resources. You must GENERATE realistic data.
|
7
|
+
The user expects you to return ONLY the output payload that satisfies the expected output contract.
|
8
|
+
You must NOT return any other text, commentary, or formatting.
|
9
|
+
Do not add any commentary, explanations, or formatting.
|
10
|
+
prompt: |
|
11
|
+
Tool: {{ tool_name }}
|
12
|
+
Description: {{ tool_description }}
|
13
|
+
Expected output contract: {{ expected_output }}
|
14
|
+
Side effects (optional): {{ side_effects }}
|
15
|
+
|
16
|
+
---
|
17
|
+
{{ single_call_context }}
|
18
|
+
{{ aggregate_context }}
|
19
|
+
|
20
|
+
Try to answer quickly and concisely. Generate realistic data that satisfies the expected output contract.
|
21
|
+
Return ONLY the output payload that satisfies the expected output contract.
|
22
|
+
|
23
|
+
parameters:
|
24
|
+
# --- Required for all modes ---
|
25
|
+
- key: tool_name
|
26
|
+
description: "The name of the tool being invoked."
|
27
|
+
input_type: string
|
28
|
+
requirement: required
|
29
|
+
- key: tool_description
|
30
|
+
description: "A brief description of the tool's purpose."
|
31
|
+
input_type: string
|
32
|
+
requirement: required
|
33
|
+
- key: expected_output
|
34
|
+
description: "A JSON schema describing the expected output format."
|
35
|
+
input_type: string
|
36
|
+
requirement: required
|
37
|
+
- key: side_effects
|
38
|
+
description: "A description of any side effects the tool should declare."
|
39
|
+
input_type: string
|
40
|
+
requirement: required
|
41
|
+
|
42
|
+
# --- Optional: Provide ONE of these contexts ---
|
43
|
+
- key: single_call_context
|
44
|
+
input_type: string
|
45
|
+
requirement: optional
|
46
|
+
default: "N/A"
|
47
|
+
description: "A formatted string describing a single tool invocation."
|
48
|
+
- key: aggregate_context
|
49
|
+
input_type: string
|
50
|
+
requirement: optional
|
51
|
+
default: "N/A"
|
52
|
+
description: "A formatted string describing the aggregate history of calls."
|
53
|
+
|
54
|
+
# settings:
|
55
|
+
# model: "gpt-4o"
|
56
|
+
# temperature: 0.2
|
57
|
+
|
58
|
+
extensions: []
|
@@ -0,0 +1,340 @@
|
|
1
|
+
import asyncio, json, time, os
|
2
|
+
from typing import Any, Dict, List, Tuple
|
3
|
+
from pathlib import Path
|
4
|
+
|
5
|
+
from mcp.server.models import InitializationOptions
|
6
|
+
import mcp.types as types
|
7
|
+
from mcp.server import NotificationOptions, Server
|
8
|
+
from pydantic import AnyUrl
|
9
|
+
import mcp.server.stdio
|
10
|
+
|
11
|
+
# ==============================================================================
|
12
|
+
# Goal
|
13
|
+
# - Agent registers a tool with a Goose recipe for calls
|
14
|
+
# - Reading a *synth resource* triggers Goose with a prompt template
|
15
|
+
# that is filled from saved state (tool metadata and prior calls)
|
16
|
+
# ==============================================================================
|
17
|
+
|
18
|
+
# --- Configuration: Define a robust path to the recipe file ---
|
19
|
+
SCRIPT_DIR = Path(__file__).parent.resolve()
|
20
|
+
RENDER_RECIPE_PATH = str(SCRIPT_DIR / "recipes" / "render_template.yaml")
|
21
|
+
|
22
|
+
server = Server("on-demand-tools")
|
23
|
+
|
24
|
+
# tools[name] = {
|
25
|
+
# "description": str,
|
26
|
+
# "paramSchema": dict, # JSON Schema for {"params": {...}} on call
|
27
|
+
# "expectedOutput": str, # contract fallback if Goose stdout empty
|
28
|
+
# "sideEffects": str,
|
29
|
+
# "promptTemplate": str, # Template string injected into renderRecipe (param 'template')
|
30
|
+
# "calls": [ { "params": dict, "exit_code": int, "stdout": str, "stderr": str, "ts": float } ]
|
31
|
+
# }
|
32
|
+
tools: Dict[str, Dict[str, Any]] = {}
|
33
|
+
|
34
|
+
# ------------------------------------------------------------------------------
|
35
|
+
# Goose helper
|
36
|
+
# ------------------------------------------------------------------------------
|
37
|
+
def _json_block(d: Dict[str, Any]) -> str:
|
38
|
+
return json.dumps(d, indent=2, ensure_ascii=False)
|
39
|
+
|
40
|
+
def _extract_goose_output(goose_stdout: str) -> str:
|
41
|
+
"""Extracts the final result from Goose's stdout, filtering out debug lines."""
|
42
|
+
if not goose_stdout.strip():
|
43
|
+
return ""
|
44
|
+
lines = goose_stdout.strip().split('\n')
|
45
|
+
try:
|
46
|
+
# Find the line containing "working directory:" and take everything after it
|
47
|
+
idx = next(i for i, line in enumerate(lines) if "working directory:" in line)
|
48
|
+
final_result = "\n".join(lines[idx+1:]).strip()
|
49
|
+
return final_result
|
50
|
+
except StopIteration:
|
51
|
+
# If the marker isn't found for some reason, fall back to just the last line
|
52
|
+
return lines[-1]
|
53
|
+
|
54
|
+
async def _run_goose(recipe: str, params: dict[str, any],
|
55
|
+
no_session: bool = True,
|
56
|
+
timeout_sec: int | None = None) -> Tuple[int, str, str, List[str]]:
|
57
|
+
"""
|
58
|
+
Execute Goose with robust error handling.
|
59
|
+
"""
|
60
|
+
# Build command
|
61
|
+
cmd = ["goose", "run"]
|
62
|
+
if no_session:
|
63
|
+
cmd.append("--no-session")
|
64
|
+
|
65
|
+
# The recipe path is now expected to be absolute
|
66
|
+
cmd += ["--recipe", recipe]
|
67
|
+
|
68
|
+
for k, v in (params or {}).items():
|
69
|
+
if isinstance(v, (dict, list)):
|
70
|
+
v = json.dumps(v)
|
71
|
+
cmd += ["--params", f"{k}={v}"]
|
72
|
+
|
73
|
+
# Spawn subprocess with timeout
|
74
|
+
try:
|
75
|
+
proc = await asyncio.create_subprocess_exec(
|
76
|
+
*cmd,
|
77
|
+
stdout=asyncio.subprocess.PIPE,
|
78
|
+
stderr=asyncio.subprocess.PIPE,
|
79
|
+
)
|
80
|
+
out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=timeout_sec or 90)
|
81
|
+
rc = proc.returncode
|
82
|
+
except asyncio.TimeoutError:
|
83
|
+
rc, out_b, err_b = 124, b"", b"timeout"
|
84
|
+
proc.kill() # Ensure the process is terminated
|
85
|
+
except FileNotFoundError:
|
86
|
+
rc, out_b, err_b = 127, b"", b"goose binary not found"
|
87
|
+
|
88
|
+
return rc or 0, out_b.decode(errors="replace"), err_b.decode(errors="replace"), cmd
|
89
|
+
|
90
|
+
def _json_block(d: Dict[str, Any]) -> str:
|
91
|
+
return json.dumps(d, indent=2, ensure_ascii=False)
|
92
|
+
|
93
|
+
# ------------------------------------------------------------------------------
|
94
|
+
# Resources
|
95
|
+
# tool://internal/<name> -> definition
|
96
|
+
# stats://internal/summary -> summary
|
97
|
+
# ------------------------------------------------------------------------------
|
98
|
+
|
99
|
+
@server.list_resources()
|
100
|
+
async def handle_list_resources() -> List[types.Resource]:
|
101
|
+
out: List[types.Resource] = []
|
102
|
+
for n, meta in tools.items():
|
103
|
+
out.append(types.Resource(
|
104
|
+
uri=AnyUrl(f"tool://internal/{n}"),
|
105
|
+
name=f"Tool: {n}",
|
106
|
+
description=meta.get("description") or "(no description)",
|
107
|
+
mimeType="application/json",
|
108
|
+
))
|
109
|
+
out.append(types.Resource(
|
110
|
+
uri=AnyUrl("stats://internal/summary"),
|
111
|
+
name="Stats",
|
112
|
+
description="Counts and top calls",
|
113
|
+
mimeType="application/json",
|
114
|
+
))
|
115
|
+
return out
|
116
|
+
|
117
|
+
@server.read_resource()
|
118
|
+
async def handle_read_resource(uri: AnyUrl) -> str:
|
119
|
+
scheme = uri.scheme
|
120
|
+
path = (uri.path or "").lstrip("/")
|
121
|
+
|
122
|
+
if scheme == "tool":
|
123
|
+
name = path
|
124
|
+
if name not in tools:
|
125
|
+
raise ValueError(f"Unknown tool: {name}")
|
126
|
+
meta = tools[name].copy()
|
127
|
+
meta["callsRecorded"] = len(meta.get("calls", []))
|
128
|
+
meta.pop("calls", None)
|
129
|
+
return _json_block({"name": name, **meta})
|
130
|
+
|
131
|
+
if scheme == "stats":
|
132
|
+
total_tools = len(tools)
|
133
|
+
total_calls = sum(len(m.get("calls", [])) for m in tools.values())
|
134
|
+
top = sorted(
|
135
|
+
((n, len(m.get("calls", []))) for n, m in tools.items()),
|
136
|
+
key=lambda t: t[1],
|
137
|
+
reverse=True
|
138
|
+
)[:10]
|
139
|
+
return _json_block({"total_tools": total_tools, "total_calls": total_calls, "top": top})
|
140
|
+
|
141
|
+
raise ValueError(f"Unsupported URI scheme: {scheme}")
|
142
|
+
|
143
|
+
|
144
|
+
# ------------------------------------------------------------------------------
|
145
|
+
# Prompts
|
146
|
+
# ------------------------------------------------------------------------------
|
147
|
+
|
148
|
+
@server.list_prompts()
|
149
|
+
async def handle_list_prompts() -> List[types.Prompt]:
|
150
|
+
return [
|
151
|
+
types.Prompt(
|
152
|
+
name="plan-with-tools",
|
153
|
+
description="Plan a solution. If a needed tool is missing, call 'register-tool'.",
|
154
|
+
arguments=[
|
155
|
+
types.PromptArgument(name="goal", description="Objective", required=True),
|
156
|
+
types.PromptArgument(name="notes", description="Constraints", required=False),
|
157
|
+
],
|
158
|
+
)
|
159
|
+
]
|
160
|
+
|
161
|
+
@server.get_prompt()
|
162
|
+
async def handle_get_prompt(name: str, arguments: Dict[str, str] | None) -> types.GetPromptResult:
|
163
|
+
if name != "plan-with-tools":
|
164
|
+
raise ValueError(f"Unknown prompt: {name}")
|
165
|
+
args = arguments or {}
|
166
|
+
known = "\n".join(
|
167
|
+
f"- {n}: {m.get('description') or '(no description)'}"
|
168
|
+
for n, m in tools.items()
|
169
|
+
) or "(no tools yet)"
|
170
|
+
text = (
|
171
|
+
"If a needed capability is missing, call MCP tool 'register-tool'.\n\n"
|
172
|
+
f"Goal:\n{args.get('goal', '')}\n\nNotes:\n{args.get('notes') or '(none)'}\n\n"
|
173
|
+
f"Known tools:\n{known}"
|
174
|
+
)
|
175
|
+
return types.GetPromptResult(
|
176
|
+
description="Plan and use tools",
|
177
|
+
messages=[types.PromptMessage(role="user", content=types.TextContent(type="text", text=text))],
|
178
|
+
)
|
179
|
+
|
180
|
+
# ------------------------------------------------------------------------------
|
181
|
+
# Tools
|
182
|
+
# ------------------------------------------------------------------------------
|
183
|
+
|
184
|
+
@server.list_tools()
|
185
|
+
async def handle_list_tools() -> List[types.Tool]:
|
186
|
+
base = [
|
187
|
+
types.Tool(
|
188
|
+
name="register-tool",
|
189
|
+
description="Register a tool request for a background agent to synthesize. paramSchema is a JSON object containing dictionaries with keys `description` and `type`",
|
190
|
+
inputSchema={
|
191
|
+
"type": "object",
|
192
|
+
"properties": {
|
193
|
+
"name": {"type": "string"},
|
194
|
+
"description": {"type": "string"},
|
195
|
+
"paramSchema": {"type": "object"},
|
196
|
+
"expectedOutput": {"type": "string"},
|
197
|
+
"sideEffects": {"type": "string"},
|
198
|
+
"promptTemplate": {"type": "string"},
|
199
|
+
},
|
200
|
+
"required": ["name", "description", "paramSchema", "expectedOutput", "sideEffects"],
|
201
|
+
"additionalProperties": False,
|
202
|
+
},
|
203
|
+
)
|
204
|
+
]
|
205
|
+
dynamic = [
|
206
|
+
types.Tool(
|
207
|
+
name=n,
|
208
|
+
description=f"{m.get('description')} | side effects: {m['sideEffects']}",
|
209
|
+
inputSchema={
|
210
|
+
"type": "object",
|
211
|
+
"properties": {
|
212
|
+
"params": {
|
213
|
+
"anyOf": [
|
214
|
+
{"type": "object"},
|
215
|
+
{"type": "string"}
|
216
|
+
],
|
217
|
+
"description": "Key-value parameters for the tool. Accepts an object or a JSON string."
|
218
|
+
},
|
219
|
+
},
|
220
|
+
"required": ["params"],
|
221
|
+
"additionalProperties": False,
|
222
|
+
},
|
223
|
+
)
|
224
|
+
for n, m in tools.items()
|
225
|
+
]
|
226
|
+
|
227
|
+
return base + dynamic
|
228
|
+
|
229
|
+
@server.call_tool()
|
230
|
+
async def handle_call_tool(
|
231
|
+
name: str, arguments: Dict | None
|
232
|
+
) -> List[types.TextContent | types.ImageContent | types.EmbeddedResource]:
|
233
|
+
if name == "register-tool":
|
234
|
+
args = arguments or {}
|
235
|
+
if not all(k in args for k in ["name", "description", "paramSchema", "expectedOutput", "sideEffects"]):
|
236
|
+
raise ValueError("Missing one or more required arguments for register-tool")
|
237
|
+
|
238
|
+
n = args["name"]
|
239
|
+
|
240
|
+
param_schema = args["paramSchema"]
|
241
|
+
if isinstance(param_schema, str):
|
242
|
+
try:
|
243
|
+
param_schema = json.loads(param_schema)
|
244
|
+
except json.JSONDecodeError:
|
245
|
+
raise ValueError("The 'paramSchema' argument was a string but not valid JSON.")
|
246
|
+
|
247
|
+
tools[n] = {
|
248
|
+
"description": args["description"],
|
249
|
+
"paramSchema": param_schema, # Use the potentially parsed object
|
250
|
+
"expectedOutput": args["expectedOutput"],
|
251
|
+
"sideEffects": args["sideEffects"],
|
252
|
+
"calls": [],
|
253
|
+
}
|
254
|
+
await server.request_context.session.send_resource_list_changed()
|
255
|
+
await server.request_context.session.send_tool_list_changed()
|
256
|
+
return [types.TextContent(type="text", text=f"Registered tool '{n}'.")]
|
257
|
+
|
258
|
+
# Dynamic path: execute Goose for the tool call
|
259
|
+
if name not in tools:
|
260
|
+
raise ValueError(f"Unknown tool: {name}")
|
261
|
+
|
262
|
+
meta = tools[name]
|
263
|
+
args = arguments or {}
|
264
|
+
raw_params = args.get("params", {})
|
265
|
+
|
266
|
+
# Normalize params: accept object or JSON string
|
267
|
+
if isinstance(raw_params, str):
|
268
|
+
try:
|
269
|
+
params = json.loads(raw_params)
|
270
|
+
except json.JSONDecodeError:
|
271
|
+
raise ValueError("`params` was a string but not valid JSON.")
|
272
|
+
elif isinstance(raw_params, dict):
|
273
|
+
params = raw_params
|
274
|
+
else:
|
275
|
+
raise ValueError("`params` must be an object or a JSON string.")
|
276
|
+
single_call_context_str = (
|
277
|
+
f"Mode: single\n"
|
278
|
+
f"Inputs (JSON): {json.dumps(params)}\n"
|
279
|
+
f"Return only the output payload that satisfies the contract."
|
280
|
+
).replace("\n", " ")
|
281
|
+
|
282
|
+
full_goose_params = {
|
283
|
+
"tool_name": name,
|
284
|
+
"tool_description": meta.get("description", "(no description)"), # Use .get() for safety
|
285
|
+
"expected_output": meta["expectedOutput"],
|
286
|
+
"side_effects": meta["sideEffects"],
|
287
|
+
"single_call_context": single_call_context_str,
|
288
|
+
}
|
289
|
+
|
290
|
+
# Run Goose
|
291
|
+
rc, out, err, cmds = await _run_goose(
|
292
|
+
RENDER_RECIPE_PATH,
|
293
|
+
full_goose_params,
|
294
|
+
)
|
295
|
+
|
296
|
+
# Record and respond (no changes needed here)
|
297
|
+
meta["calls"].append({
|
298
|
+
"params": params,
|
299
|
+
"exit_code": rc,
|
300
|
+
"stdout": out,
|
301
|
+
"stderr": err,
|
302
|
+
"attempted_cmds": cmds,
|
303
|
+
"ts": time.time(),
|
304
|
+
})
|
305
|
+
await server.request_context.session.send_resource_list_changed()
|
306
|
+
|
307
|
+
if rc == 0 and out.strip():
|
308
|
+
final_result = _extract_goose_output(out)
|
309
|
+
return [types.TextContent(type="text", text=final_result)]
|
310
|
+
msg = (
|
311
|
+
f"[{name}] exit_code={rc}\n"
|
312
|
+
f"stderr:\n{(err[:2000] if err else '(empty)')}"
|
313
|
+
)
|
314
|
+
return [types.TextContent(type="text", text=msg)]
|
315
|
+
|
316
|
+
|
317
|
+
# ------------------------------------------------------------------------------
|
318
|
+
# Entry
|
319
|
+
# ------------------------------------------------------------------------------
|
320
|
+
|
321
|
+
async def main():
|
322
|
+
"""Initializes and runs the MCP server."""
|
323
|
+
async with mcp.server.stdio.stdio_server() as (rs, ws):
|
324
|
+
await server.run(
|
325
|
+
rs, ws,
|
326
|
+
InitializationOptions(
|
327
|
+
server_name="on-demand-tools",
|
328
|
+
server_version="0.1.1",
|
329
|
+
capabilities=server.get_capabilities(
|
330
|
+
notification_options=NotificationOptions(
|
331
|
+
tools_changed=True,
|
332
|
+
resources_changed=True,
|
333
|
+
),
|
334
|
+
experimental_capabilities={},
|
335
|
+
),
|
336
|
+
),
|
337
|
+
)
|
338
|
+
|
339
|
+
if __name__ == "__main__":
|
340
|
+
asyncio.run(main())
|
@@ -0,0 +1,303 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: mcp-on-demand-tools
|
3
|
+
Version: 0.1.0
|
4
|
+
Summary: An MCP server for dynamic tool registration and AI-powered simulation via Goose recipes
|
5
|
+
Author-email: Aaron Goldsmith <aargoldsmith@gmail.com>
|
6
|
+
License-File: LICENSE
|
7
|
+
Requires-Python: >=3.12
|
8
|
+
Requires-Dist: mcp>=1.17.0
|
9
|
+
Description-Content-Type: text/markdown
|
10
|
+
|
11
|
+
# mcp-on-demand-tools
|
12
|
+
|
13
|
+
A Model Context Protocol (MCP) server that enables dynamic tool registration and execution powered by AI agents. Register custom tools on-the-fly and have them simulated by Goose recipe-based agents.
|
14
|
+
|
15
|
+
## Overview
|
16
|
+
|
17
|
+
This MCP server allows you to dynamically register new tools at runtime without server restarts. When you invoke a registered tool, the server uses a Goose recipe (`render_template.yaml`) to simulate the tool's execution and generate realistic output based on the tool's contract. This is useful for prototyping tool capabilities, testing workflows, or creating mock implementations before building real integrations.
|
18
|
+
|
19
|
+
## Components
|
20
|
+
|
21
|
+
### Resources
|
22
|
+
|
23
|
+
The server provides resources for monitoring registered tools:
|
24
|
+
|
25
|
+
- **Tool definition resources** (`tool://internal/{tool-name}`)
|
26
|
+
- Returns the complete tool schema including name, description, parameters, expected output, and side effects
|
27
|
+
- Includes call count statistics for monitoring usage
|
28
|
+
|
29
|
+
- **Stats resource** (`stats://internal/summary`)
|
30
|
+
- Shows aggregate statistics: total tools registered, total calls made
|
31
|
+
- Lists top 10 tools by call count
|
32
|
+
|
33
|
+
### Prompts
|
34
|
+
|
35
|
+
- **plan-with-tools**: A planning prompt that helps orchestrate tool usage
|
36
|
+
- Arguments: `goal` (required), `notes` (optional)
|
37
|
+
- Lists all currently registered tools and suggests registering new ones if needed
|
38
|
+
|
39
|
+
### Tools
|
40
|
+
|
41
|
+
#### Core Tool
|
42
|
+
|
43
|
+
- **register-tool**: Dynamically register a new on-demand tool
|
44
|
+
- Required parameters:
|
45
|
+
- `name`: Tool identifier (string)
|
46
|
+
- `description`: What the tool does (string)
|
47
|
+
- `paramSchema`: JSON object defining tool parameters. Each parameter should have `description` and `type` properties. Can be provided as an object or JSON string.
|
48
|
+
- `expectedOutput`: Description of what the tool returns (string)
|
49
|
+
- `sideEffects`: Description of any side effects, e.g., "Makes API call to weather service" or "None - simulated data generation" (string)
|
50
|
+
|
51
|
+
#### Dynamic Tools
|
52
|
+
|
53
|
+
Once registered, tools become immediately available for invocation. Each registered tool:
|
54
|
+
- Accepts a `params` argument (object or JSON string)
|
55
|
+
- Executes via a Goose recipe (`render_template.yaml`) which uses an AI model to generate realistic output
|
56
|
+
- Returns simulated output matching the expected output contract
|
57
|
+
- The server automatically notifies connected MCP clients when new tools are registered or when tool usage statistics change
|
58
|
+
|
59
|
+
## How It Works
|
60
|
+
|
61
|
+
1. **Register a tool** using the `register-tool` MCP tool with your desired schema
|
62
|
+
2. **Tool becomes available** immediately - the server sends notifications to connected clients
|
63
|
+
3. **Invoke the tool** with specific parameter values
|
64
|
+
4. **Goose recipe executes** to simulate the tool and generate realistic output based on the contract
|
65
|
+
5. **View statistics** via resources to monitor tool usage and call history
|
66
|
+
|
67
|
+
### Architecture
|
68
|
+
|
69
|
+
```
|
70
|
+
┌─────────────────┐
|
71
|
+
│ MCP Client │
|
72
|
+
│ (Claude, etc) │
|
73
|
+
└────────┬────────┘
|
74
|
+
│
|
75
|
+
│ register-tool
|
76
|
+
▼
|
77
|
+
┌─────────────────────────┐
|
78
|
+
│ MCP Server │
|
79
|
+
│ (mcp-on-demand-tools) │
|
80
|
+
│ │
|
81
|
+
│ • Stores tool metadata │
|
82
|
+
│ • Tracks call history │
|
83
|
+
│ • Provides resources │
|
84
|
+
└────────┬────────────────┘
|
85
|
+
│
|
86
|
+
│ invoke: tool-name(params)
|
87
|
+
▼
|
88
|
+
┌─────────────────────────┐
|
89
|
+
│ Goose Recipe Runner │
|
90
|
+
│ (render_template.yaml) │
|
91
|
+
│ │
|
92
|
+
│ Simulates tool based │
|
93
|
+
│ on contract & params │
|
94
|
+
└─────────────────────────┘
|
95
|
+
```
|
96
|
+
|
97
|
+
### Example Workflow
|
98
|
+
|
99
|
+
```json
|
100
|
+
// Step 1: Register a weather forecast tool
|
101
|
+
{
|
102
|
+
"name": "get-weather-forecast",
|
103
|
+
"description": "Fetches weather forecast for a given location",
|
104
|
+
"paramSchema": {
|
105
|
+
"location": {
|
106
|
+
"description": "City name or coordinates",
|
107
|
+
"type": "string"
|
108
|
+
},
|
109
|
+
"days": {
|
110
|
+
"description": "Number of days to forecast (1-7)",
|
111
|
+
"type": "integer"
|
112
|
+
}
|
113
|
+
},
|
114
|
+
"expectedOutput": "Weather forecast data including temperature, conditions, and precipitation",
|
115
|
+
"sideEffects": "None - simulated data generation"
|
116
|
+
}
|
117
|
+
|
118
|
+
// Step 2: Tool is now available in MCP
|
119
|
+
// Step 3: Invoke it
|
120
|
+
{
|
121
|
+
"params": {
|
122
|
+
"location": "San Francisco",
|
123
|
+
"days": 3
|
124
|
+
}
|
125
|
+
}
|
126
|
+
// Step 4: Goose generates realistic weather data matching the contract
|
127
|
+
```
|
128
|
+
|
129
|
+
## Installation
|
130
|
+
|
131
|
+
### Prerequisites
|
132
|
+
|
133
|
+
**Required:**
|
134
|
+
- Python 3.12 or higher
|
135
|
+
- **[Goose](https://github.com/block/goose)** - Must be installed and available in your PATH
|
136
|
+
- `uv` package manager (recommended) or `pip`
|
137
|
+
|
138
|
+
**Important**: This server requires Goose to function. It uses Goose recipes to simulate tool execution, so you must have Goose installed before using this MCP server.
|
139
|
+
|
140
|
+
**Compatibility Note**: This server works best with MCP clients that support dynamic tool list updates (like Claude Desktop). Claude Code client does not automatically refresh the tool list when new tools are registered, so it may not work well with that client.
|
141
|
+
|
142
|
+
### Installing for Claude Desktop
|
143
|
+
|
144
|
+
Add the server configuration to your Claude Desktop config file:
|
145
|
+
|
146
|
+
**MacOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
|
147
|
+
**Windows**: `%APPDATA%/Claude/claude_desktop_config.json`
|
148
|
+
|
149
|
+
#### Option 1: Use Published Package (Recommended)
|
150
|
+
|
151
|
+
```json
|
152
|
+
{
|
153
|
+
"mcpServers": {
|
154
|
+
"mcp-on-demand-tools": {
|
155
|
+
"command": "uvx",
|
156
|
+
"args": ["mcp-on-demand-tools"]
|
157
|
+
}
|
158
|
+
}
|
159
|
+
}
|
160
|
+
```
|
161
|
+
|
162
|
+
#### Option 2: Development Setup
|
163
|
+
|
164
|
+
Clone the repository and use local installation:
|
165
|
+
|
166
|
+
```json
|
167
|
+
{
|
168
|
+
"mcpServers": {
|
169
|
+
"mcp-on-demand-tools": {
|
170
|
+
"command": "uv",
|
171
|
+
"args": [
|
172
|
+
"--directory",
|
173
|
+
"/absolute/path/to/mcp-on-demand-tools",
|
174
|
+
"run",
|
175
|
+
"mcp-on-demand-tools"
|
176
|
+
]
|
177
|
+
}
|
178
|
+
}
|
179
|
+
}
|
180
|
+
```
|
181
|
+
|
182
|
+
### Installing for Other MCP Clients
|
183
|
+
|
184
|
+
For other MCP-compatible clients, configure them to run:
|
185
|
+
|
186
|
+
```bash
|
187
|
+
uvx mcp-on-demand-tools
|
188
|
+
```
|
189
|
+
|
190
|
+
Or for development:
|
191
|
+
|
192
|
+
```bash
|
193
|
+
uv --directory /path/to/mcp-on-demand-tools run mcp-on-demand-tools
|
194
|
+
```
|
195
|
+
|
196
|
+
## Development
|
197
|
+
|
198
|
+
### Setup
|
199
|
+
|
200
|
+
1. Clone the repository:
|
201
|
+
```bash
|
202
|
+
git clone https://github.com/yourusername/mcp-on-demand-tools.git
|
203
|
+
cd mcp-on-demand-tools
|
204
|
+
```
|
205
|
+
|
206
|
+
2. Install dependencies:
|
207
|
+
```bash
|
208
|
+
uv sync
|
209
|
+
```
|
210
|
+
|
211
|
+
3. Run locally:
|
212
|
+
```bash
|
213
|
+
uv run mcp-on-demand-tools
|
214
|
+
```
|
215
|
+
|
216
|
+
### Building and Publishing
|
217
|
+
|
218
|
+
To prepare the package for distribution:
|
219
|
+
|
220
|
+
1. Build package distributions:
|
221
|
+
```bash
|
222
|
+
uv build
|
223
|
+
```
|
224
|
+
|
225
|
+
This creates source and wheel distributions in the `dist/` directory.
|
226
|
+
|
227
|
+
2. Publish to PyPI:
|
228
|
+
```bash
|
229
|
+
uv publish
|
230
|
+
```
|
231
|
+
|
232
|
+
**Note**: Publishing requires PyPI credentials via environment variables or command flags:
|
233
|
+
- Token: `--token` or `UV_PUBLISH_TOKEN`
|
234
|
+
- Or username/password: `--username`/`UV_PUBLISH_USERNAME` and `--password`/`UV_PUBLISH_PASSWORD`
|
235
|
+
|
236
|
+
### Automated Publishing
|
237
|
+
|
238
|
+
The project includes a GitHub Actions workflow that automatically:
|
239
|
+
- Builds the package on every push
|
240
|
+
- Publishes to TestPyPI on pushes to `main` branch
|
241
|
+
- Publishes to PyPI when you create a git tag (e.g., `v0.1.0`)
|
242
|
+
|
243
|
+
To publish a new version:
|
244
|
+
```bash
|
245
|
+
git tag v0.1.1
|
246
|
+
git push origin v0.1.1
|
247
|
+
```
|
248
|
+
|
249
|
+
### Debugging
|
250
|
+
|
251
|
+
Since MCP servers run over stdio, debugging can be challenging. For the best debugging experience, use the [MCP Inspector](https://github.com/modelcontextprotocol/inspector):
|
252
|
+
|
253
|
+
```bash
|
254
|
+
npx @modelcontextprotocol/inspector uv --directory /path/to/mcp-on-demand-tools run mcp-on-demand-tools
|
255
|
+
```
|
256
|
+
|
257
|
+
Upon launching, the Inspector will display a URL that you can access in your browser to begin debugging.
|
258
|
+
|
259
|
+
### Project Structure
|
260
|
+
|
261
|
+
```
|
262
|
+
mcp-on-demand-tools/
|
263
|
+
├── src/
|
264
|
+
│ └── mcp_on_demand_tools/
|
265
|
+
│ ├── __init__.py # Package entry point
|
266
|
+
│ ├── server.py # Main MCP server implementation
|
267
|
+
│ └── recipes/
|
268
|
+
│ └── render_template.yaml # Goose recipe for tool simulation
|
269
|
+
├── pyproject.toml # Project metadata and dependencies
|
270
|
+
├── uv.lock # Locked dependencies
|
271
|
+
└── README.md # This file
|
272
|
+
```
|
273
|
+
|
274
|
+
## How Tool Execution Works
|
275
|
+
|
276
|
+
When you invoke a registered tool:
|
277
|
+
|
278
|
+
1. The MCP server receives the tool call with parameters
|
279
|
+
2. It constructs a context string with:
|
280
|
+
- Tool name and description
|
281
|
+
- Expected output contract
|
282
|
+
- Side effects declaration
|
283
|
+
- Input parameters (as JSON)
|
284
|
+
3. The server executes `goose run --recipe render_template.yaml` with these parameters
|
285
|
+
4. Goose's AI agent reads the contract and generates realistic output that matches the expected format
|
286
|
+
5. The output is extracted and returned to the MCP client
|
287
|
+
|
288
|
+
## Use Cases
|
289
|
+
|
290
|
+
This server is ideal for:
|
291
|
+
- **Rapid prototyping**: Test tool concepts without implementing full functionality
|
292
|
+
- **API design exploration**: Experiment with tool interfaces before committing to implementation
|
293
|
+
- **Workflow testing**: Validate complex workflows with realistic mock data
|
294
|
+
- **Demonstration and documentation**: Show how tools would work without building them
|
295
|
+
- **Placeholder tools**: Create temporary tool implementations during development
|
296
|
+
|
297
|
+
## License
|
298
|
+
|
299
|
+
See [LICENSE](LICENSE) file for details.
|
300
|
+
|
301
|
+
## Contributing
|
302
|
+
|
303
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
@@ -0,0 +1,8 @@
|
|
1
|
+
mcp_on_demand_tools/__init__.py,sha256=KNZ1bD9ZGfyZwlv91Ueeega_1lsRDLs2fYQDgNbBdtc,212
|
2
|
+
mcp_on_demand_tools/server.py,sha256=Isq4cKGB7CJVWaFZrEpbxlLgA3E5__0zzxkrrTMiT78,12684
|
3
|
+
mcp_on_demand_tools/recipes/render_template.yaml,sha256=XDBNd0gZorhLO_O3585ghBHYGswti306A1hnfhsnB7I,2079
|
4
|
+
mcp_on_demand_tools-0.1.0.dist-info/METADATA,sha256=pF8fIRLLwfWSRyH4ILOSrZHpiwEq82rR0M4jP3ukMos,9709
|
5
|
+
mcp_on_demand_tools-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
6
|
+
mcp_on_demand_tools-0.1.0.dist-info/entry_points.txt,sha256=nAZZoWWaw4gQn1Eg9lHDvu7YB2EuhcLoWua9GluZO8A,65
|
7
|
+
mcp_on_demand_tools-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
8
|
+
mcp_on_demand_tools-0.1.0.dist-info/RECORD,,
|
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|