scriptling.mcp.tool
MCP tool helper library for authoring MCP tools in scriptling. This sub-library provides functions for parameter access and result handling when implementing tool scripts.
For the MCP client library (connecting to MCP servers), see scriptling.mcp.
Enabling
The tool helpers are a separate, optional sub-library. Register it explicitly when needed:
mcp.RegisterToolHelpers(sl) // Registers scriptling.mcp.toolEnvironment Variables
MCP tool helpers read and write environment variables set by the MCP tool execution environment:
__mcp_params: Dictionary containing tool parameters.__mcp_response: String containing the tool’s result.
Available Functions
| Function | Description |
|---|---|
get_int(name, default=0) |
Get an integer parameter |
get_float(name, default=0.0) |
Get a float parameter |
get_string(name, default="") |
Get a string parameter (trims whitespace) |
get_bool(name, default=False) |
Get a boolean parameter |
get_list(name, default=None) |
Get a list parameter (splits strings by comma) |
get_string_list(name, default=None) |
Get a string array parameter |
get_int_list(name, default=None) |
Get an integer array parameter |
get_float_list(name, default=None) |
Get a float array parameter |
get_bool_list(name, default=None) |
Get a boolean array parameter |
get_request() |
Get the HTTP request this call arrived on, or None |
request_context() |
Get the context dict set by the middleware (empty dict if none) |
return_string(text) |
Return a string result and stop execution |
return_object(obj) |
Return an object as JSON and stop execution |
return_toon(obj) |
Return an object as TOON and stop execution |
return_error(message) |
Return an error message and stop execution |
Parameter Access Functions
mcp.tool.get_int(name, default=0)
Gets an integer parameter from the tool’s input arguments. Returns the default value if the parameter doesn’t exist or can’t be coerced to an integer.
Parameters:
name(str): Parameter name.default(int, optional): Default value if the parameter is missing. Default:0.
Returns: int
import scriptling.mcp.tool as tool
project_id = tool.get_int("project_id", 0)
limit = tool.get_int("limit", 100)mcp.tool.get_float(name, default=0.0)
Gets a float parameter from the tool’s input arguments. Returns the default value if the parameter doesn’t exist or can’t be coerced to a float.
Parameters:
name(str): Parameter name.default(float, optional): Default value if the parameter is missing. Default:0.0.
Returns: float
import scriptling.mcp.tool as tool
price = tool.get_float("price", 0.0)
percentage = tool.get_float("percentage", 100.0)mcp.tool.get_string(name, default="")
Gets a string parameter from the tool’s input arguments. Automatically trims whitespace, and returns the default value if the parameter doesn’t exist, is empty, or is whitespace-only.
Parameters:
name(str): Parameter name.default(str, optional): Default value if the parameter is missing or empty. Default:"".
Returns: str
import scriptling.mcp.tool as tool
name = tool.get_string("name", "guest")
query = tool.get_string("query")mcp.tool.get_bool(name, default=False)
Gets a boolean parameter from the tool’s input arguments. Handles "true"/"false" strings (case-insensitive) and numeric 0/1.
Parameters:
name(str): Parameter name.default(bool, optional): Default value if the parameter is missing or can’t be converted. Default:False.
Returns: bool
import scriptling.mcp.tool as tool
enabled = tool.get_bool("enabled", True)
verbose = tool.get_bool("verbose")mcp.tool.get_list(name, default=None)
Gets a list parameter from the tool’s input arguments. If the value is a string, splits it by comma.
Parameters:
name(str): Parameter name.default(list, optional): Default value if the parameter is missing. Default: empty list.
Returns: list
import scriptling.mcp.tool as tool
ids = tool.get_list("ids") # "1,2,3" → ["1", "2", "3"]
tags = tool.get_list("tags", ["all"]) # "tag1, tag2" → ["tag1", "tag2"]mcp.tool.get_string_list(name, default=None)
Gets a string array parameter (array:string type) from the tool’s input arguments.
Parameters:
name(str): Parameter name.default(list, optional): Default value if the parameter is missing. Default: empty list.
Returns: list of str
import scriptling.mcp.tool as tool
args = tool.get_string_list("arguments") # ["--verbose", "-o", "file.txt"]
tags = tool.get_string_list("tags", ["default"])mcp.tool.get_int_list(name, default=None)
Gets an integer array parameter (array:int type) from the tool’s input arguments.
Parameters:
name(str): Parameter name.default(list, optional): Default value if the parameter is missing. Default: empty list.
Returns: list of int
import scriptling.mcp.tool as tool
ids = tool.get_int_list("ids") # [1, 2, 3, 4]
ports = tool.get_int_list("ports", [8080])mcp.tool.get_float_list(name, default=None)
Gets a float array parameter (array:float type) from the tool’s input arguments.
Parameters:
name(str): Parameter name.default(list, optional): Default value if the parameter is missing. Default: empty list.
Returns: list of float
import scriptling.mcp.tool as tool
prices = tool.get_float_list("prices") # [19.99, 29.99, 39.99]
weights = tool.get_float_list("weights", [1.0])mcp.tool.get_bool_list(name, default=None)
Gets a boolean array parameter (array:bool type) from the tool’s input arguments.
Parameters:
name(str): Parameter name.default(list, optional): Default value if the parameter is missing. Default: empty list.
Returns: list of bool
import scriptling.mcp.tool as tool
flags = tool.get_bool_list("flags") # [true, false, true]
options = tool.get_bool_list("options", [False])Request Access Functions
When the MCP server is served over HTTP, these give tool scripts a look at the HTTP request the call arrived on — the same one the server’s middleware saw. Over the stdio transport there is no HTTP request.
mcp.tool.get_request()
Returns the HTTP request this tool call is being served for: a Request object with method, path, headers, query, remote_addr and context. Returns None over stdio or anywhere else outside a served request.
Returns: Request or None
import scriptling.mcp.tool as tool
req = tool.get_request()
if req != None:
log(req.remote_addr + " called this tool")mcp.tool.request_context()
Returns the context dict the middleware populated for this request — e.g. request.context["user"] = name after authenticating. Always a dict: empty when no middleware ran or it set nothing, so .get(name, default) is always safe. Each call gets its own copy, so writes from the handler are local and never visible to other handlers.
Returns: dict
import scriptling.mcp.tool as tool
user = tool.request_context().get("user", "anonymous")
tool.return_string("hello " + user)Result Functions
Result functions set the tool’s response and immediately stop script execution using SystemExit. No code after these calls will execute.
mcp.tool.return_string(text)
Returns a string result and stops execution.
Parameters:
text(str): The result text.
Returns: None: execution stops before returning to caller.
import scriptling.mcp.tool as tool
tool.return_string("Search completed successfully")
# Code here will not executemcp.tool.return_object(obj)
Returns an object as JSON and stops execution.
Parameters:
obj(dictorlist): The result object.
Returns: None: execution stops before returning to caller.
import scriptling.mcp.tool as tool
tool.return_object({"status": "success", "count": 42})
# Code here will not executemcp.tool.return_toon(obj)
Returns an object encoded as TOON (compact text format optimized for LLMs) and stops execution.
Parameters:
obj(dictorlist): The result object.
Returns: None: execution stops before returning to caller.
import scriptling.mcp.tool as tool
tool.return_toon({"result": data})
# Code here will not executemcp.tool.return_error(message)
Returns an error message and stops execution with error code 1.
Parameters:
message(str): Error message.
Returns: None: execution stops before returning to caller.
import scriptling.mcp.tool as tool
if not customer_id:
tool.return_error("Customer ID is required")
# Code here will not execute
tool.return_error("Customer not found")Complete Tool Example
# Recommended: import as alias (cleanest)
import scriptling.mcp.tool as tool
# Get parameters with defaults
name = tool.get_string("name", "guest")
age = tool.get_int("age", 0)
verbose = tool.get_bool("verbose", False)
# Validate inputs
if age < 0:
tool.return_error("Age must be positive")
# Process and return result
result = {
"greeting": f"Hello, {name}!",
"age": age,
"category": "adult" if age >= 18 else "minor"
}
if verbose:
import time
result["timestamp"] = time.time()
tool.return_object(result)Usage in Tool Scripts
When implementing MCP tools, the execution environment sets __mcp_params before running your script:
# Tool script: greet_user.py
import scriptling.mcp.tool as tool
name = tool.get_string("name", "guest")
age = tool.get_int("age", 0)
tool.return_object({
"message": f"Hello, {name}! You are {age} years old."
})The tool execution environment will:
- Set the
__mcp_paramsdict with tool parameters. - Run the script.
- Catch the
SystemExitexception fromreturn_*functions. - Extract the result from
__mcp_response. - Return it to the MCP client.
Go Helper Function
For Go applications that need to run MCP tool scripts, the RunToolScript helper function simplifies the process:
import (
"context"
"github.com/paularlott/scriptling"
"github.com/paularlott/scriptling/extlibs/mcp"
)
// Create scriptling instance and register tool helpers
sl := scriptling.New()
mcp.RegisterToolHelpers(sl)
// Define tool script
script := `
import scriptling.mcp.tool as tool
name = tool.get_string("name", "guest")
age = tool.get_int("age", 0)
tool.return_object({
"message": f"Hello, {name}! You are {age} years old."
})
`
// Run the tool with parameters
params := map[string]interface{}{
"name": "Alice",
"age": 30,
}
response, exitCode, err := mcp.RunToolScript(context.Background(), sl, script, params)
// response: JSON string with the result
// exitCode: 0 for success, 1 for error
// err: Go error if execution failedFunction signature:
func RunToolScript(
ctx context.Context,
sl *scriptling.Scriptling,
script string,
params map[string]interface{}
) (response string, exitCode int, err error)Parameters:
ctx: Context for cancellation and timeouts.sl: Scriptling instance (must have tool helpers registered).script: The tool script code.params: Map of parameter name to value.
Returns:
response: The tool response from__mcp_response(usually JSON).exitCode:0for success,1for error.err: Go error if execution failed (nilforexitCode0).
Best Practices
- Always use defaults: Provide sensible default values for optional parameters.
- Validate early: Check required parameters and return errors immediately.
- Return quickly: Use
return_*functions as soon as you have a result. - Handle errors: Use
return_error()for user-facing error messages. - Choose the right format: Use
return_stringfor text,return_objectfor structured data,return_toonfor LLM-optimized output.
Security Considerations
This is an extended library, requiring registration in Go, see Library Registration.
scriptling.mcp.tool itself has no implicit network, filesystem, or process access: it only reads __mcp_params and writes __mcp_response. Risk depends entirely on what the tool script you write does with those parameters.
See Also
- scriptling.mcp: MCP client for connecting to MCP servers
- scriptling.ai: AI client and completion functions
- scriptling.ai.agent: Building AI agents with automatic tool execution