Repository navigation
Expand file tree
/
Copy pathpy_mcp.cpp
More file actions
438 lines (379 loc) · 16.8 KB
/
Copy pathpy_mcp.cpp
File metadata and controls
438 lines (379 loc) · 16.8 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/* SPDX-FileCopyrightText: 2025 LichtFeld Studio Authors
* SPDX-License-Identifier: GPL-3.0-or-later */
#include "py_mcp.hpp"
#include "core/base64.hpp"
#include "core/error_envelope.hpp"
#include "core/logger.hpp"
#include "mcp/mcp_protocol.hpp"
#include "mcp/mcp_tools.hpp"
#include "py_error.hpp"
#include <nanobind/stl/optional.h>
#include <nanobind/stl/string.h>
#include <nanobind/stl/tuple.h>
#include <nanobind/stl/vector.h>
#include <algorithm>
#include <string_view>
namespace lfs::python {
namespace {
std::string python_type_to_json_type(const std::string& py_type) {
if (py_type == "int")
return "integer";
if (py_type == "float")
return "number";
if (py_type == "bool")
return "boolean";
if (py_type == "str")
return "string";
if (py_type.starts_with("list[int]") || py_type.starts_with("List[int]"))
return "array:integer";
if (py_type.starts_with("list[float]") || py_type.starts_with("List[float]"))
return "array:number";
if (py_type.starts_with("list") || py_type.starts_with("List"))
return "array";
return "string";
}
mcp::json build_json_schema_property(const std::string& json_type, const std::string& description) {
mcp::json prop;
if (json_type.starts_with("array:")) {
prop["type"] = "array";
std::string item_type = json_type.substr(6);
prop["items"] = mcp::json{{"type", item_type}};
} else if (json_type == "array") {
prop["type"] = "array";
} else {
prop["type"] = json_type;
}
if (!description.empty()) {
prop["description"] = description;
}
return prop;
}
mcp::json python_value_to_json(nb::handle obj) {
if (obj.is_none()) {
return nullptr;
}
if (nb::isinstance<nb::bool_>(obj)) {
return nb::cast<bool>(obj);
}
if (nb::isinstance<nb::int_>(obj)) {
return nb::cast<int64_t>(obj);
}
if (nb::isinstance<nb::float_>(obj)) {
return nb::cast<double>(obj);
}
if (nb::isinstance<nb::str>(obj)) {
return nb::cast<std::string>(obj);
}
if (nb::isinstance<nb::list>(obj)) {
mcp::json arr = mcp::json::array();
nb::list lst = nb::cast<nb::list>(obj);
for (size_t i = 0; i < lst.size(); ++i) {
arr.push_back(python_value_to_json(lst[i]));
}
return arr;
}
if (nb::isinstance<nb::dict>(obj)) {
mcp::json dict = mcp::json::object();
nb::dict d = nb::cast<nb::dict>(obj);
nb::object items = d.attr("items")();
for (auto item : items) {
nb::tuple tup = nb::cast<nb::tuple>(item);
std::string key = nb::cast<std::string>(tup[0]);
dict[key] = python_value_to_json(tup[1]);
}
return dict;
}
return nb::cast<std::string>(nb::str(obj));
}
nb::object json_to_python(const mcp::json& j) {
if (j.is_null()) {
return nb::none();
}
if (j.is_boolean()) {
return nb::cast(j.get<bool>());
}
if (j.is_number_integer()) {
return nb::cast(j.get<int64_t>());
}
if (j.is_number_float()) {
return nb::cast(j.get<double>());
}
if (j.is_string()) {
return nb::cast(j.get<std::string>());
}
if (j.is_array()) {
nb::list lst;
for (const auto& el : j) {
lst.append(json_to_python(el));
}
return lst;
}
if (j.is_object()) {
nb::dict d;
for (auto& [k, v] : j.items()) {
d[k.c_str()] = json_to_python(v);
}
return d;
}
return nb::none();
}
struct PyToolInfo {
std::string name;
std::string description;
nb::object callback;
mcp::json properties;
std::vector<std::string> required;
};
std::vector<std::string> registered_tools_;
std::mutex tools_mutex_;
std::string resolve_python_tool_name(std::string name) {
name = mcp::normalize_tool_name(std::move(name));
if (!name.starts_with("plugin_")) {
name = "plugin_" + name;
}
return name;
}
std::string python_tool_registry_name(const std::string& name) {
const std::string wire_name = resolve_python_tool_name(name);
return "plugin." + wire_name.substr(std::string_view("plugin_").size());
}
std::string resolve_call_tool_name(std::string name) {
name = mcp::normalize_tool_name(std::move(name));
if (name.starts_with("plugin_")) {
return name;
}
const std::string plugin_name = "plugin_" + name;
std::lock_guard lock(tools_mutex_);
if (std::find(registered_tools_.begin(), registered_tools_.end(), plugin_name) != registered_tools_.end()) {
return plugin_name;
}
return name;
}
mcp::McpTool create_tool_from_info(const PyToolInfo& info) {
return mcp::McpTool{
.name = info.name,
.description = info.description,
.input_schema = {
.type = "object",
.properties = info.properties,
.required = info.required}};
}
mcp::ToolRegistry::ToolHandler create_python_handler(nb::object callback) {
return [callback](const mcp::json& args) -> mcp::json {
nb::gil_scoped_acquire gil;
try {
nb::dict py_args = nb::cast<nb::dict>(json_to_python(args));
nb::object result = callback(**py_args);
return python_value_to_json(result);
} catch (nb::python_error& e) {
const lfs::Error error = contain_python_callback(e, PyCallbackPolicy::FailOwner);
std::string message = std::string("Python tool error: ") + std::string(error.user_message());
return mcp::json{{"error", core::to_wire_envelope(error)}, {"error_message", std::move(message)}};
} catch (const std::exception& e) {
const lfs::Error error = contain_cxx_callback(e.what(), PyCallbackPolicy::FailOwner);
std::string message = std::string("Python tool error: ") + std::string(error.user_message());
return mcp::json{{"error", core::to_wire_envelope(error)}, {"error_message", std::move(message)}};
}
};
}
PyToolInfo extract_tool_info(nb::callable fn, const std::string& name, const std::string& description) {
PyToolInfo info;
info.callback = fn;
nb::object inspect = nb::module_::import_("inspect");
nb::object sig = inspect.attr("signature")(fn);
nb::object params = sig.attr("parameters");
std::string tool_name = name;
if (tool_name.empty()) {
tool_name = nb::cast<std::string>(fn.attr("__name__"));
}
info.name = python_tool_registry_name(tool_name);
std::string tool_desc = description;
if (tool_desc.empty()) {
nb::object doc = fn.attr("__doc__");
if (!doc.is_none()) {
tool_desc = nb::cast<std::string>(doc);
}
}
info.description = tool_desc;
mcp::json properties = mcp::json::object();
std::vector<std::string> required;
nb::object items = params.attr("items")();
for (auto item : items) {
nb::tuple tup = nb::cast<nb::tuple>(item);
std::string param_name = nb::cast<std::string>(tup[0]);
nb::object param = tup[1];
nb::object annotation = param.attr("annotation");
nb::object default_val = param.attr("default");
nb::object empty = inspect.attr("Parameter").attr("empty");
std::string json_type = "string";
if (!annotation.is(empty)) {
std::string type_name = nb::cast<std::string>(nb::str(annotation));
if (type_name.find("int") != std::string::npos && type_name.find("list") == std::string::npos) {
json_type = "integer";
} else if (type_name.find("float") != std::string::npos) {
json_type = "number";
} else if (type_name.find("bool") != std::string::npos) {
json_type = "boolean";
} else if (type_name.find("str") != std::string::npos) {
json_type = "string";
} else if (type_name.find("list") != std::string::npos || type_name.find("List") != std::string::npos) {
json_type = "array";
}
}
properties[param_name] = build_json_schema_property(json_type, "");
bool has_default = !default_val.is(empty);
if (!has_default) {
required.push_back(param_name);
}
}
info.properties = properties;
info.required = required;
return info;
}
void register_python_tool(nb::callable fn, const std::string& name, const std::string& description) {
PyToolInfo info = extract_tool_info(fn, name, description);
mcp::McpTool tool = create_tool_from_info(info);
auto handler = create_python_handler(info.callback);
mcp::ToolRegistry::instance().register_tool(std::move(tool), std::move(handler));
const auto registered_tools = mcp::ToolRegistry::instance().list_tools();
const auto registered = std::find_if(
registered_tools.begin(),
registered_tools.end(),
[&info](const mcp::McpTool& candidate) { return candidate.name == info.name; });
if (registered == registered_tools.end()) {
return;
}
const std::string wire_name = mcp::normalize_tool_name(info.name);
std::lock_guard lock(tools_mutex_);
if (std::find(registered_tools_.begin(), registered_tools_.end(), wire_name) == registered_tools_.end()) {
registered_tools_.push_back(wire_name);
}
LOG_INFO("Registered Python MCP tool: {}", wire_name);
}
void unregister_python_tool(const std::string& name) {
const std::string wire_name = resolve_python_tool_name(name);
mcp::ToolRegistry::instance().unregister_tool(wire_name);
std::lock_guard lock(tools_mutex_);
registered_tools_.erase(
std::remove(registered_tools_.begin(), registered_tools_.end(), wire_name),
registered_tools_.end());
LOG_INFO("Unregistered Python MCP tool: {}", wire_name);
}
std::vector<std::string> list_python_tools() {
std::lock_guard lock(tools_mutex_);
return registered_tools_;
}
std::vector<std::string> list_all_tools() {
auto tools = mcp::ToolRegistry::instance().list_tools();
std::vector<std::string> names;
names.reserve(tools.size());
for (const auto& tool : tools) {
names.push_back(mcp::normalize_tool_name(tool.name));
}
return names;
}
nb::list describe_all_tools() {
nb::list result;
for (const auto& tool : mcp::ToolRegistry::instance().list_tools()) {
result.append(json_to_python(mcp::tool_to_json(tool)));
}
return result;
}
std::vector<std::string> list_all_resources() {
auto resources = mcp::ResourceRegistry::instance().list_resources();
std::vector<std::string> uris;
uris.reserve(resources.size());
for (const auto& resource : resources) {
uris.push_back(resource.uri);
}
return uris;
}
nb::list read_resource_contents(const std::string& uri) {
auto contents = mcp::ResourceRegistry::instance().read_resource(uri);
if (!contents) {
throw nb::value_error(contents.error().c_str());
}
nb::list result;
for (const auto& content : *contents) {
nb::dict item;
item["uri"] = content.uri;
if (content.mime_type) {
item["mime_type"] = *content.mime_type;
}
if (std::holds_alternative<std::string>(content.content)) {
const auto& string_content = std::get<std::string>(content.content);
const bool is_blob =
content.mime_type && content.mime_type->starts_with("image/");
if (is_blob) {
item["blob"] = string_content;
} else {
item["text"] = string_content;
}
} else {
item["blob"] = core::base64_encode(std::get<std::vector<uint8_t>>(content.content));
}
result.append(std::move(item));
}
return result;
}
} // namespace
void register_mcp(nb::module_& m) {
auto mcp_module = m.def_submodule("mcp", "MCP (Model Context Protocol) tool registration");
mcp_module.def(
"register_tool",
[](nb::callable fn, const std::string& name, const std::string& description) {
register_python_tool(fn, name, description);
},
nb::arg("fn"), nb::arg("name") = "", nb::arg("description") = "",
"Register a Python function as an MCP tool");
mcp_module.def(
"unregister_tool",
[](const std::string& name) { unregister_python_tool(name); },
nb::arg("name"),
"Unregister an MCP tool");
mcp_module.def(
"list_tools", []() { return list_all_tools(); },
"List all registered shared capabilities/tools");
mcp_module.def(
"list_python_tools", []() { return list_python_tools(); },
"List Python-provided MCP tools registered through this module");
mcp_module.def(
"describe_tools", []() { return describe_all_tools(); },
"Describe all registered shared capabilities/tools");
mcp_module.def(
"list_resources", []() { return list_all_resources(); },
"List all registered MCP resources");
mcp_module.def(
"read_resource", [](const std::string& uri) { return read_resource_contents(uri); },
nb::arg("uri"),
"Read one registered MCP resource");
mcp_module.def(
"call_tool",
[](const std::string& name, nb::handle args) {
mcp::json json_args = mcp::json::object();
if (!args.is_none()) {
json_args = python_value_to_json(args);
if (!json_args.is_object()) {
throw nb::value_error("call_tool args must be a dict/object");
}
}
return json_to_python(
mcp::ToolRegistry::instance().call_tool(
resolve_call_tool_name(name),
json_args,
lfs::OperationId::generate()));
},
nb::arg("name"), nb::arg("args") = nb::none(),
"Invoke a registered shared capability/tool");
mcp_module.def(
"tool",
[](const std::string& name, const std::string& description) {
return nb::cpp_function([name, description](nb::callable fn) -> nb::callable {
register_python_tool(fn, name, description);
return fn;
});
},
nb::arg("name") = "", nb::arg("description") = "",
"Decorator to register a function as an MCP tool");
}
} // namespace lfs::python