use serde_json::{Value, json};
use crate::host;
pub fn mcp_definitions(host_tools: &[host::Tool]) -> Vec<Value> {
let stubs: Vec<String> = host_tools
.iter()
.filter(|tool| is_tool_id(&tool.id))
.map(format_stub)
.collect();
let execute_description = format!(
"Runs a Python script in the sandbox's session and answers with the value of its last \
expression as {{\"status\": \"finished\", \"value\": ...}}, or {{\"status\": \"failed\", \
\"error\": ..., \"calls\": [...]}}. Globals persist from one script to the next. A \
script still waiting on a tool when the wait ends answers {{\"status\": \"running\", \
\"run_id\": ...}}: poll that run id for the rest.\n\nThe script calls these tools as \
Python functions, which take keyword arguments only:\n\n{}",
stubs.join("\n\n")
);
vec![
json!({
"name": "execute",
"description": execute_description,
"inputSchema": {
"type": "object",
"properties": {
"code": {"type": "string", "description": "The Python script to run."},
"restart": {
"type": "boolean",
"default": false,
"description": "Start the session fresh first, with no globals, dropping any run still running. The status then carries \"restarted\": true.",
},
},
"required": ["code"],
"additionalProperties": false,
},
}),
json!({
"name": "poll",
"description": "Waits for the run that execute left running, and answers as execute does.",
"inputSchema": {
"type": "object",
"properties": {
"run_id": {"type": "integer", "description": "The run id of a running status."},
},
"required": ["run_id"],
"additionalProperties": false,
},
}),
]
}
pub fn openai_definitions(host_tools: &[host::Tool]) -> Vec<Value> {
mcp_definitions(host_tools)
.into_iter()
.map(|definition| {
json!({
"type": "function",
"function": {
"name": definition["name"],
"description": definition["description"],
"parameters": definition["inputSchema"],
},
})
})
.collect()
}
fn format_stub(tool: &host::Tool) -> String {
let required = tool.input_schema["required"].as_array();
let is_required = |arg: &str| required.is_some_and(|ids| ids.iter().any(|id| id == arg));
let mut args: Vec<(&String, &Value)> = tool.input_schema["properties"]
.as_object()
.into_iter()
.flatten()
.collect();
args.sort_unstable_by_key(|(arg, _)| (!is_required(arg), *arg));
let takes_kwargs = !args.iter().all(|(arg, _)| is_python_argument(arg));
let args: Vec<String> = args
.into_iter()
.map(|(arg, arg_schema)| {
let python_type = to_python_type(arg_schema);
if is_required(arg) {
format!("{arg}: {python_type}")
} else {
format!("{arg}: {python_type} | None = None")
}
})
.collect();
let (args, docstring) = if takes_kwargs {
let arg_lines = args.join("\n");
let docstring = format!("{}\nKeyword arguments:\n{arg_lines}", tool.description);
("**kwargs: Any".to_owned(), docstring)
} else if args.is_empty() {
(String::new(), tool.description.clone())
} else {
(format!("*, {}", args.join(", ")), tool.description.clone())
};
let mut docstring = docstring.replace('\\', r"\\");
if docstring.contains(r#"""""#) || docstring.ends_with('"') {
docstring = docstring.replace('"', r#"\""#);
}
let docstring = docstring.replace('\n', "\n ");
format!(
"def {}({args}) -> Any:\n \"\"\"{docstring}\"\"\"",
tool.id
)
}
fn to_python_type(value_schema: &Value) -> String {
if let Some(values) = value_schema["enum"].as_array() {
let literals: Vec<String> = values.iter().map(to_python_literal).collect();
return format!("Literal[{}]", literals.join(", "));
}
match value_schema["type"].as_str() {
Some("string") => "str".to_owned(),
Some("integer") => "int".to_owned(),
Some("number") => "float".to_owned(),
Some("boolean") => "bool".to_owned(),
Some("array") => format!("list[{}]", to_python_type(&value_schema["items"])),
Some("object") => "dict[str, Any]".to_owned(),
_ => "Any".to_owned(),
}
}
fn to_python_literal(value: &Value) -> String {
match value {
Value::Bool(true) => "True".to_owned(),
Value::Bool(false) => "False".to_owned(),
Value::Null => "None".to_owned(),
_ => value.to_string(),
}
}
const PYTHON_KEYWORDS: &[&str] = &[
"False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue",
"def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import",
"in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
"with", "yield",
];
#[rustfmt::skip]
const PYTHON_BUILTINS: &[&str] = &[
"ArithmeticError", "AssertionError", "AttributeError", "BaseException", "BaseExceptionGroup",
"BlockingIOError", "BrokenPipeError", "BufferError", "BytesWarning", "ChildProcessError",
"ConnectionAbortedError", "ConnectionError", "ConnectionRefusedError", "ConnectionResetError",
"DeprecationWarning", "EOFError", "Ellipsis", "EncodingWarning", "EnvironmentError",
"Exception", "ExceptionGroup", "FileExistsError", "FileNotFoundError", "FloatingPointError",
"FrozenInstanceError", "FutureWarning", "GeneratorExit", "IOError", "ImportError",
"ImportWarning", "IndentationError", "IndexError", "InterruptedError", "IsADirectoryError",
"KeyError", "KeyboardInterrupt",
"LookupError", "MemoryError", "ModuleNotFoundError", "NameError", "NotADirectoryError",
"NotImplemented", "NotImplementedError", "OSError", "OverflowError",
"PendingDeprecationWarning", "PermissionError", "ProcessLookupError",
"PythonFinalizationError", "RecursionError", "ReferenceError", "ResourceWarning",
"RuntimeError", "RuntimeWarning", "StopAsyncIteration", "StopIteration", "SyntaxError",
"SyntaxWarning", "SystemError", "SystemExit", "TabError", "TimeoutError", "TypeError",
"UnboundLocalError", "UnicodeDecodeError", "UnicodeEncodeError", "UnicodeError",
"UnicodeTranslateError", "UnicodeWarning", "UserWarning", "ValueError", "Warning",
"WindowsError", "ZeroDivisionError", "abs", "aiter", "all", "anext", "any", "ascii", "bin",
"bool", "breakpoint", "bytearray", "bytes", "callable", "chr", "classmethod", "compile",
"complex", "copyright", "credits", "delattr", "dict", "dir", "divmod", "enumerate", "eval",
"exec", "exit", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr",
"hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len",
"license", "list", "locals", "map", "max", "memoryview", "min", "next", "object", "oct",
"open", "ord", "pow", "print", "property", "quit", "range", "repr", "reversed", "round", "set",
"setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "vars",
"zip",
];
pub fn is_tool_id(id: &str) -> bool {
is_python_argument(id) && !PYTHON_BUILTINS.contains(&id)
}
fn is_python_argument(arg: &str) -> bool {
!arg.is_empty()
&& !arg.starts_with(|c: char| c.is_ascii_digit())
&& arg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
&& !PYTHON_KEYWORDS.contains(&arg)
&& arg != "__debug__"
}