MCP Server How To

ScriptLangCore can act as an MCP (Model Context Protocol) server, exposing script-defined tools to AI assistants like Claude Desktop, VS Code Copilot, or any MCP-compatible host.

Quick start

ScriptLangCore.exe --mcp --allowed-dir C:\Projects\my-data

The server loads all .slc files from the tools/ directory next to the executable (or from the directories named by --tools-dir), registers any tools defined via RegisterMcpTool(), and starts listening for JSON-RPC 2.0 messages over stdio (default) or HTTP+SSE (with --port).

A tool script is EXECUTED, so the directory must hold tool scripts and nothing else. Loading a tool means running the file: one that waits, loops, or opens a dialog hangs startup, and one that faults natively ends the process before the server ever listens. Keep instruments, samples and scratch files in another folder, or point --tools-dir at a directory that holds only tools.
Not just for Claude. MCP is an open protocol (JSON-RPC 2.0 over stdio or SSE). The same config works with VS Code extensions (Cline, Continue, GitHub Copilot), IDEs (IntelliJ via Continue), editors (Cursor, Windsurf), and custom clients built with the mcp Python/TypeScript SDKs. The server doesn't know or care which client connected, it speaks standard MCP.

Table of contents

Command-line reference Writing tools RegisterMcpTool API Argument marshalling Path sandbox Transport modes REPL + MCP Configuration REPL commands MCP Protocol Methods Full example Troubleshooting

Command-line reference

ScriptLangCore.exe --mcp [--port <number>] [--allowed-dir <path>] [--tools-dir <path>]
ScriptLangCore.exe --mcp-bc [--port <number>] [--allowed-dir <path>] [--tools-dir <dir-of-bundles>]

--mcp-bc takes every --mcp flag and changes one thing: the tools directory is read as compiled *.slcbc bundles instead of *.slc sources. Each bundle is loaded and RUN, so its top-level RegisterMcpTool() calls register exactly as a script's do.

FlagRequiredDescription
--mcpYesStart in MCP server mode instead of CLI/REPL
--port <N>NoEnable HTTP+SSE transport on http://localhost:N/. Default: stdio
--url <prefix>NoFull URL prefix (supports https://). Overrides --port. Example: --url https://*:8765/
--allowed-dir <path>No (recommended)Restrict file operations to this directory. Can be repeated.
--tools-dir <path>NoLoad tool scripts from this directory INSTEAD of tools/. Can be repeated. A relative path is resolved against the current directory.
--replNoStart MCP server in background + launch interactive REPL for testing.

Examples

stdio ScriptLangCore.exe --mcp --allowed-dir C:\Projects
http  ScriptLangCore.exe --mcp --port 8765 --allowed-dir C:\Projects
multi ScriptLangCore.exe --mcp --allowed-dir C:\Data --allowed-dir D:\Work
https ScriptLangCore.exe --mcp --url https://+:8765/ --allowed-dir C:\Projects
tools ScriptLangCore.exe --mcp --tools-dir C:\MyTools --allowed-dir C:\Projects
repl  ScriptLangCore.exe --mcp --port 8765 --repl --allowed-dir C:\Projects
--repl requires --port (SSE). Both the REPL and the stdio MCP server read from stdin and cannot coexist in stdio mode. --repl without --port auto-defaults to http://localhost:8765/. For pure stdio (Claude Desktop, VS Code), omit --repl.

Writing tools

Each tool is a script function registered via RegisterMcpTool(). Place your scripts in the tools/ directory alongside ScriptLangCore.exe, or in a directory of your own named by --tools-dir. Only tool scripts belong there: every file in that directory is executed at startup.

Minimal example

tools/hello.slc
RegisterMcpTool("hello", "Greet a person by name.",
    (string name) => {
        return "Hello, " + name + "!";
    },
    '{ "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] }'
);

What happens when the server starts

  1. ScriptLangCore.exe --mcp scans tools/ (or each --tools-dir) for *.slc files
  2. ScriptLangCore.exe --mcp-bc does the same with *.slcbc instead: each bundle is LOADED AND RUN, so its top-level RegisterMcpTool() calls still register. A compiled bundle is not merely a library, which is what makes a tools directory of compiled bundles work.
  3. Each file is RUN, from its first line: RegisterMcpTool() registers the tool in the MCP tool registry. That is why the directory must hold tool scripts and nothing else: the load is an execution, so a script that blocks hangs the startup and one that faults natively ends the process
  4. When the AI sends tools/call, the server looks up the tool by name, marshals the JSON arguments to script values, invokes the function, and returns the result as JSON

RegisterMcpTool API

RegisterMcpTool(name, description, handler, [schema])
ParameterTypeRequiredDescription
namestringYesTool name used in tools/call. Must be unique.
descriptionstringYesHuman-readable description shown to the AI.
handlerFunctionYesScript function invoked when the tool is called.
schemastringNoJSON Schema describing the input parameters.

Handler function signature

(string path, string content) => {
    // Return a string, it becomes the MCP response content.
    return "result";
}

Argument marshalling

When the AI calls a tool, the MCP server reads the parameter names from the function declaration, looks up matching keys in the arguments JSON object, and converts values:

JSON typeScript type
stringstring
numberint or double
true / falsebool
nullnull
object / arraystring (raw JSON)

If the function has no named parameters, the entire arguments object is passed as a single JSON string.

Path sandbox

The --allowed-dir flag restricts which files tools can access. The sandbox only checks string arguments that look like file paths (contain /, \, ., or start with a drive letter like C:). Plain strings like "hello" are allowed through. Any tool that tries to read or write a file outside the allowed directory receives an error:

{
  "error": {
    "code": -32000,
    "message": "Access denied: 'D:\\secrets.txt' is outside allowed directories."
  }
}

How it works

Without --allowed-dir, tools have unrestricted filesystem access, the sandbox is opt-in.

Middleware pipeline

Middleware intercepts every tool call before the handler runs. Register middleware with mcp.Use:

tools/mcp_middleware.slc
// Logging middleware
mcp.Use((McpContext ctx, Action next) => {
    print("  [middleware] tool=" + ctx.ToolName + " args=" + ctx.Args.Count);
    next();
});

Pipeline flow

ActionEffect
next()Continue to the next middleware (or tool handler)
ctx.ErrorMessage = "msg"Stop the pipeline, returns error to caller
ctx.Result = valueBypass tool handler, return this value directly
No next() callSilent short-circuit, pipeline stops

Multiple middleware, onion order

mcp.Use((McpContext ctx, Action next) => { print("A"); next(); print("a"); });
mcp.Use((McpContext ctx, Action next) => { print("B"); next(); print("b"); });
mcp.Use((McpContext ctx, Action next) => { print("C"); });
// Execution order: A → B → C → b → a

Blocking a tool

mcp.Use((McpContext ctx, Action next) => {
    if (ctx.ToolName == "delete_file") {
        ctx.ErrorMessage = "delete_file is blocked by policy";
        return;  // don't call next()
    }
    next();
});

Context properties

PropertyTypeDescription
ctx.ToolNamestringName of the tool being called
ctx.ArgslistArguments passed to the tool
ctx.Resultobject?Set to return a value (bypasses handler)

tcp.Use is also available for TCP connection middleware: it runs for every connection the engine's own TCP server accepts (Server.Create + Server.Start). Its context is a TcpContext (provides RemoteAddress, Close()).

HTTP server middleware

http.Use registers middleware for non-MCP HTTP requests on the same port. Every request that isn't POST / or GET /sse flows through the HTTP middleware pipeline.

tools/mcp_httpserver.slc
// Logging middleware
http.Use((HttpContext ctx, Action next) => {
    print("  [http] " + ctx.HttpMethod + " " + ctx.Url);
    next();
});

// Route: GET /hello
http.Use((HttpContext ctx, Action next) => {
    if (ctx.Url == "/hello" && ctx.HttpMethod == "GET") {
        ctx.ResponseBody = "Hello from middleware!";
        ctx.ResponseStatus = 200;
        return;  // short-circuit
    }
    next();
});

Context properties

PropertyTypeDescription
ctx.HttpMethodstringHTTP method (GET, POST, etc.)
ctx.UrlstringRequest path (e.g., /hello)
ctx.Bodystring?Request body (for POST/PUT)
ctx.ResponseStatusintSet to change HTTP status (default 200)
ctx.ResponseBodystring?Set to define the response text
ctx.ResponseBytesbyte[]?Set to return raw binary data (overrides ResponseBody)
ctx.ErrorMessagestring?Set to return HTTP 500 with error

Pipeline flow

Same onion-order as mcp.Use: next() continues, no next() short-circuits, ctx.ErrorMessage returns 500 error carrying its text as the body, ctx.ResponseBody + ResponseStatus define the response. A status the ENGINE sets carries no body, the way ASP.NET Core does it: a path nothing answers is a 404 with Content-Length: 0, and an unhandled exception is a 500 with no body (the cause goes to the server's log). Without any middleware at all, every non-MCP path returns 404.

Testing from curl

# Welcome page
curl http://localhost:8765/

# Current server time
curl http://localhost:8765/time

# Server status (memory)
curl http://localhost:8765/status

# Hello world
curl http://localhost:8765/hello

# POST JSON echo
curl -X POST http://localhost:8765/echo -H "Content-Type: application/json" -d '{"message":"hello"}'
# → Echo: {"message":"hello"}

# POST raw text
curl -X POST http://localhost:8765/echo -d "hello"
# → Echo: hello

# Download a file (text or binary) via HTTP middleware and save to disk
curl -X POST http://localhost:8765/download -d "README.md" -o README.md

# Download a binary file, exact bytes preserved via ResponseBytes
curl -X POST http://localhost:8765/download -d "publish-aot/ScriptLangCore.exe" -o ScriptLangCore.exe

Testing from browser DevTools

// GET routes
fetch("http://localhost:8765/time").then(r => r.text()).then(console.log)
// → "2026-07-10 19:45:30"

fetch("http://localhost:8765/status").then(r => r.text()).then(console.log)
// → "Status: running\nMemory: 12345678 bytes"

// POST with JSON body
fetch("http://localhost:8765/echo", {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({hello: "world"})
}).then(r => r.text()).then(console.log)
// → "Echo: {\"hello\":\"world\"}"
Routes are shared with MCP. All requests arrive on the single HTTP listener. MCP paths (POST / and GET /sse) are handled first; everything else passes through the HTTP middleware pipeline. To start the server: ScriptLangCore.exe --mcp --port 8765.

REPL + MCP combo

Use --repl to run the MCP server in a background thread while keeping the interactive REPL. This is useful for debugging, you can call tool functions directly from the REPL while the server handles AI requests.

repl ScriptLangCore.exe --mcp --port 8765 --repl --allowed-dir C:\Projects

From the REPL you can:

Transport modes

Stdio (default)

The server reads JSON-RPC messages from stdin and writes responses to stdout. This works with Claude Desktop, VS Code, and most MCP hosts.

┌──────────────┐  stdio JSON-RPC  ┌──────────────────┐
│  AI Client   │ ◄──────────────► │  ScriptLangCore  │
└──────────────┘                  └──────────────────┘
Stdio = JSON-RPC only. In pure stdio mode (without --port or --repl), every line is read as JSON-RPC. Typing .help or other REPL commands will fail with a parse error. For interactive testing, use --repl --port 8765 instead.
Send requests from PowerShell

Pipe a JSON-RPC message to the executable:

# List tools
'{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | .\ScriptLangCore.exe --mcp

# Ping
'{"jsonrpc":"2.0","id":1,"method":"ping"}' | .\ScriptLangCore.exe --mcp

# Call a tool
'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"echo","arguments":{"message":"hi"}}}' | .\ScriptLangCore.exe --mcp

For file-based requests:

# Save request to file
Set-Content request.json '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

# Pipe the file
Get-Content request.json | .\ScriptLangCore.exe --mcp

# Capture and format the response
$response = Get-Content request.json | .\ScriptLangCore.exe --mcp
$response | ConvertFrom-Json | ConvertTo-Json -Depth 10

HTTP+SSE (--port / --url)

When --port or --url is specified, the server listens for HTTP(S) connections:

POST /     → JSON-RPC request/response (tools/call, tools/list)
GET  /sse  → Server-Sent Events stream for notifications

All other paths return 404.

Testing from a browser or HTTP client

You can call MCP tools directly from any HTTP client, no AI assistant needed.

Browser DevTools Console

Open DevTools (F12) on any page.

List tools:

fetch("http://localhost:8765/", {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({
    jsonrpc: "2.0", id: 1, method: "tools/list"
  })
}).then(r => r.json()).then(console.log)

Call a tool:

fetch("http://localhost:8765/", {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({
    jsonrpc: "2.0", id: 2, method: "tools/call",
    params: { name: "test_echo", arguments: { message: "hello from browser" } }
  })
}).then(r => r.json()).then(console.log)

More examples:

// test_add, two integers
fetch("http://localhost:8765/", {method:"POST",headers:{"Content-Type":"application/json"},
  body: JSON.stringify({jsonrpc:"2.0", id:3, method:"tools/call",
    params:{name:"test_add", arguments:{a:42, b:58}}
  })}).then(r=>r.json()).then(console.log)

// test_bool, booleans
fetch("http://localhost:8765/", {method:"POST",headers:{"Content-Type":"application/json"},
  body: JSON.stringify({jsonrpc:"2.0", id:4, method:"tools/call",
    params:{name:"test_bool", arguments:{flag:true, enabled:false}}
  })}).then(r=>r.json()).then(console.log)

// test_mixed, all types together
fetch("http://localhost:8765/", {method:"POST",headers:{"Content-Type":"application/json"},
  body: JSON.stringify({jsonrpc:"2.0", id:5, method:"tools/call",
    params:{name:"test_mixed", arguments:{name:"widget", count:5, price:9.99, active:true}}
  })}).then(r=>r.json()).then(console.log)

curl

The -d flag is required, it sets the Content-Length header. Without it, HttpListener returns HTTP 411 (Length Required).
# List tools
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

# Call a tool
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"test_echo","arguments":{"message":"hello from curl"}}}'

PowerShell

# List tools
Invoke-RestMethod -Uri http://localhost:8765/ -Method Post -Body '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' -ContentType "application/json"

# Call a tool
Invoke-RestMethod -Uri http://localhost:8765/ -Method Post -Body '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"test_echo","arguments":{"message":"hi from powershell"}}}' -ContentType "application/json"

Expected response:

{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"ECHO: hello from curl"}]}}

HTTPS setup

HttpListener supports HTTPS when a certificate is bound to the port:

# 1. Create a self-signed certificate (one time)
dotnet dev-certs https --trust

# 2. Get the certificate thumbprint (40-char hex string)
certutil -store -user My | findstr /i "sha1"
# Copy the hex string (e.g., dc40e6b404fde6c692946efbe0e679193330e830)

# 3. Bind the certificate to the port (run as Administrator)
netsh http add sslcert ipport=0.0.0.0:8765 certhash="REPLACE_WITH_ACTUAL_THUMBPRINT" appid="{00000000-0000-0000-0000-000000000000}"

# 4. Start with HTTPS
ScriptLangCore.exe --mcp --url https://+:8765/ --allowed-dir C:\Projects

HTTPS troubleshooting

Error 1312: "A specified logon session does not exist", the certificate is in the Current User store but HTTP.sys requires it in the Local Machine store.

# Export from Current User with private key
certutil -user -exportpfx -p "password" MY REPLACE_WITH_THUMBPRINT mycert.pfx

# Import into Local Machine store (run as Administrator)
certutil -importpfx -p "password" mycert.pfx

# Grant NETWORK SERVICE read access to the private key
# certlm.msc → Personal → Certificates → right-click cert →
# All Tasks → Manage Private Keys → Add NETWORK SERVICE with Read

# Now bind should work
netsh http add sslcert ipport=0.0.0.0:8765 certhash="REPLACE_WITH_ACTUAL_THUMBPRINT" appid="{00000000-0000-0000-0000-000000000000}"
For local development, if the AI assistant runs on the same machine, HTTP on localhost is safe, traffic never leaves your computer. Skip the HTTPS setup and use --port instead.

The --url flag accepts any prefix that HttpListener supports:

Configuration for AI clients

Claude Desktop

Edit claude_desktop_config.json (usually at %APPDATA%\Claude\):

{
  "mcpServers": {
    "scriptlang": {
      "command": "C:\\Tools\\ScriptLangCore.exe",
      "args": ["--mcp", "--allowed-dir", "C:\\Projects"]
    }
  }
}

VS Code (Cline / Continue)

In your VS Code extension settings for Cline or Continue:

{
  "mcpServers": {
    "scriptlang": {
      "command": "C:\\Tools\\ScriptLangCore.exe",
      "args": ["--mcp", "--allowed-dir", "C:\\Projects"]
    }
  }
}

Compatibility with other AI tools

MCP is an open protocol, it is not tied to Anthropic or Claude. Any AI tool that implements the MCP client side can connect.

Tool / EditorConfig locationSame config?
Claude Desktop%APPDATA%\Claude\claude_desktop_config.json✅ Identical JSON
Cline (VS Code)VS Code settings → mcpServers✅ Identical JSON
Continue (VS Code / IntelliJ)Settings → mcpServers✅ Identical JSON
GitHub Copilot (VS Code)VS Code settings → mcpServers✅ Identical JSON
CursorProject root → .cursor/tools.json⚠️ Different path
WindsurfSettings → MCP servers✅ Identical JSON
Custom clientAny language (Python, TS, Java)✅ Stdio or SSE

Config for Cursor

// .cursor/tools.json (place in your project root)
{
  "scriptlang": {
    "command": "C:\\Tools\\ScriptLangCore.exe",
    "args": ["--mcp", "--allowed-dir", "C:\\Projects"]
  }
}

Custom Python client (HTTP+SSE)

connect_via_sse.py
import requests

resp = requests.post("http://localhost:8765", json={
    "jsonrpc": "2.0", "id": 1, "method": "tools/list"
})
print(resp.json())

resp = requests.post("http://localhost:8765", json={
    "jsonrpc": "2.0", "id": 2, "method": "tools/call",
    "params": {"name": "read_file", "arguments": {"path": "test.txt"}}
})
print(resp.json())

Custom TypeScript client (stdio)

connect_via_stdio.ts
import { spawn } from "child_process";

const mcp = spawn("C:\\Tools\\ScriptLangCore.exe", [
  "--mcp", "--allowed-dir", "C:\\Projects"
]);

mcp.stdin.write(JSON.stringify({
  jsonrpc: "2.0", id: 1, method: "tools/list"
}) + "\n");

mcp.stdout.on("data", (data) => {
  console.log("Response:", data.toString());
});
The wire protocol is always the same, JSON-RPC 2.0 with \n-delimited messages over stdio, or HTTP POST + SSE for remote connections. The server doesn't know or care which client is connected.

MCP Protocol Methods (not tools)

The MCP server handles several protocol-level methods that don't appear in .mcp because they're not registered via RegisterMcpTool. These are built into the server and handle lifecycle, logging, and resource discovery.

Lifecycle

MethodPurpose
pingHealth check, keeps clients connected
initializeProtocol version + capability negotiation
notifications/initializedClient confirms initialization complete (no response)

The server responds to initialize with:

{
  "protocolVersion": "2025-03-26",
  "capabilities": {
    "tools": {},
    "resources": {},
    "logging": {}
  }
}

Logging

Clients can set the log verbosity level:

curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"logging/setLevel","params":{"level":"debug"}}'

Log messages go to stderr, filtered by level:

LevelShowsExample
debugEverything (headers + body)See example below
infoTool calls + errors[MCP infos] tool:system_info args:0
noticeSame as info (reserved)
warningErrors only
errorErrors only[MCP error] tool:read_file failed: ...
offNothing
Debug level output (full HTTP trace)
[2026-06-04 20:21:44][MCP debug] ↓ POST / from [::1]:65157
[2026-06-04 20:21:44][MCP debug]   Content-Length: 113
[2026-06-04 20:21:44][MCP debug]   Content-Type: application/json
[2026-06-04 20:21:44][MCP debug]   Accept: */*
[2026-06-04 20:21:44][MCP debug]   Host: localhost:8765
[2026-06-04 20:21:44][MCP debug]   User-Agent: curl/8.18.0
[2026-06-04 20:21:44][MCP debug]   Body[113]: {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"message":"hello from curl"}}}
[2026-06-04 20:21:44][MCP debug] → tools/call id=2
[2026-06-04 20:21:44][MCP infos] tool:echo args:1
Info level output (tool call only)
[2026-06-04 20:21:44][MCP infos] tool:echo args:1

RegisterMcpResource API

Resources expose read-only data via the MCP resources protocol. Register them from scripts:

RegisterMcpResource(uri, name, mimeType, handler)
ParameterTypeRequiredDescription
uristringYesUnique identifier (e.g., "info/system")
namestringYesHuman-readable name shown to the AI
mimeTypestringYesMIME type ("text/plain", "application/json")
handlerFunctionYesZero-argument function returning content as string

Handler is zero-argument, no parameters, returns the resource content as a string:

// Inline lambda
RegisterMcpResource("info/system", "System Info", "text/plain",
    () => { return "OS: " + Environment.OSVersion; }
);

// Named function also works
string myHandler() { return File.ReadAllText("README.md"); }
RegisterMcpResource("docs/readme", "README", "text/markdown", myHandler);

Resources

Resources are read-only data exposed alongside tools. Listed via resources/list, read via resources/read:

# List available resources
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"resources/list"}'

# → {"jsonrpc":"2.0","id":1,"result":{"resources":[{"uri":"info/system","name":"System Info","mimeType":"text/plain"}]}}

# Read a specific resource
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":2,"method":"resources/read","params":{"uri":"info/system"}}'

# → {"jsonrpc":"2.0","id":2,"result":{"contents":[{"uri":"info/system","mimeType":"text/plain","text":"OS: ...\nCores: 16\n..."}]}}

Tools vs Resources

Tools (tools/call)Resources (resources/read)
Use forActions, write files, modify stateData, read-only files, config, info
From .call✅ .call read_file {"path":"..."}❌ Protocol method
From curl✅ tools/call✅ resources/read
Discovery.mcp listingresources/list
ParametersRequired (tool-defined)None (handler is zero-arg)

Testing from curl

# Ping the server
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"ping"}'

# Check protocol version
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"initialize"}'

# Set debug logging
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"logging/setLevel","params":{"level":"debug"}}'

# List resources
curl -X POST http://localhost:8765/ -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"resources/list"}'

Full example

Here's a complete MCP tool script that exposes file operations to the AI:

tools/file_tools.slc
// ── Read a file ──
RegisterMcpTool("read_file", "Read the full contents of a text file.",
    (string path) => {
        if (!File.Exists(path))
            return "Error: file not found: " + path;
        return File.ReadAllText(path);
    },
    '{ "type": "object", "properties": { "path": { "type": "string" } }, "required": ["path"] }'
);

// ── Write a file ──
RegisterMcpTool("write_file", "Write text content to a file (creates or overwrites).",
    (string path, string content) => {
        File.WriteAllText(path, content);
        return "Written: " + path + " (" + content.Length + " chars)";
    },
    '{ "type": "object", "properties": { "path": { "type": "string" }, "content": { "type": "string" } }, "required": ["path", "content"] }'
);

// ── List directory ──
RegisterMcpTool("list_dir", "List all files in a directory.",
    (string dir) => {
        if (!Directory.Exists(dir))
            return "Error: directory not found: " + dir;
        var files = Directory.GetFiles(dir);
        var result = "Files in " + dir + ":\n";
        var i = 0;
        while (i < files.Count) {
            result = result + "  " + files[i] + "\n";
            i = i + 1;
        }
        return result;
    },
    '{ "type": "object", "properties": { "dir": { "type": "string" } }, "required": ["dir"] }'
);

// ── File size ──
RegisterMcpTool("file_size", "Get the size of a file in bytes.",
    (string path) => {
        if (!File.Exists(path))
            return "Error: file not found: " + path;
        var size = File.GetSize(path);
        return path + ", " + size + " bytes";
    },
    '{ "type": "object", "properties": { "path": { "type": "string" } }, "required": ["path"] }'
);

// ── System info ──
RegisterMcpTool("system_info", "Return OS and process information.",
    () => {
        var os  = Environment.OSVersion;
        var proc = Environment.ProcessorCount;
        var mem = GC.GetTotalMemory();
        return "OS: " + os + "\nCPU cores: " + proc + "\nGC memory: " + mem + " bytes";
    },
    '{ "type": "object", "properties": {} }'
);

REPL commands

Start the MCP server on a background thread with the interactive REPL for live testing:

ScriptLangCore.exe --mcp --port 8765 --repl --allowed-dir C:\Projects

Once started, the REPL provides these MCP-specific commands:

.log, set MCP log level

>>> .log debug
Log level set to: debug

>>> .log warning
Log level set to: warning

>>> .log off
Logging disabled.

Levels: debug < info < notice < warning < error. off disables logging.

.mcp, list registered tools

>>> .mcp
Registered MCP tools (6):
  read_file(path: string)                           Read the full contents of a text file from disk.
  write_file(path: string, content: string)         Write text content to a file (creates or overwrites).
  list_dir(dir: string)                             List all files in a directory.
  test_echo(message: string)                        Echo back the input (quick connectivity test).
  test_add(a: int, b: int)                          Add two numbers (tests number marshalling).
  [Protocol methods: ping, initialize, logging/setLevel, resources/list]

.call, invoke a tool directly

>>> .call test_echo {"message":"hi"}
ECHO: hi

>>> .call test_add {"a":3,"b":4}
Result: 7

>>> .call read_file {"path":"test.txt"}
(file contents)

Supported JSON argument types

JSON typeScript typeExample
stringstring.call test_echo {"message":"hello"}
integerint / long.call test_add {"a":3,"b":4}
floatdouble.call round {"value":3.14}
true / falsebool.call set_flag {"enabled":true}
nullnull.call clear {"value":null}
object / arraystring (raw JSON).call parse {"data":{"key":"val"}}

The .call command tests the same code path the AI uses, JSON-RPC → argument marshalling → InvokeScriptFunction → result formatting. Useful for debugging tool behavior without an AI client connected.

Troubleshooting

The server ends with no message, or never reaches "server started"

A tool script is executed at load, so a script in the tools directory that is not a tool is executed too. The last loading tool=<name> line names the one that did it, and there are two shapes. The process ends silently (a native fault; a DebugBreak call, for instance, is reported by the OS as STATUS_BREAKPOINT and cannot be caught), or it never gets past that line (a script that waits, loops, or opens a dialog). Move everything that is not a tool out of that directory, or point --tools-dir at a directory that holds only tools.

Server starts but tools don't appear

Check that your script files are in the tools/ directory next to ScriptLangCore.exe. The server looks for tools/*.slc relative to the executable path, and --tools-dir overrides it.

"Unknown tool" errors

Make sure RegisterMcpTool is called at the top level of your script, not inside a function. Registration runs when the script is loaded at startup.

JSON parsing errors

Verify the JSON Schema string is valid JSON. Use a linter if unsure. The schema is optional, you can omit it and the AI will infer arguments from the function signature.

File access denied

Either add the file's parent directory with --allowed-dir, or remove --allowed-dir entirely to allow unrestricted access.

Windows piping

On Windows, stdin piping from echo may not work correctly with binary executables. Use type request.json | ScriptLangCore.exe --mcp instead.