Creating a Self-Writing Lisp Server for AI Tools

The Model Context Protocol (MCP) has become the standard for connecting AI assistants to external tools, but most implementations are static. They define a fixed set of capabilities at startup and wait for requests. This works well for databases or file systems, but it feels restrictive when paired with a language as dynamic as Common Lisp. The runtime model of Lisp allows for something more fluid: a server that can define and install new tools on the fly, adapting its own capabilities to the immediate needs of the coding session.
By leveraging an AI model to generate tool definitions and evaluating them directly into the running image, you create a system that evolves during conversation. This approach, often demonstrated in projects like Octopus, allows the server to rewrite its own toolset without requiring a restart or redeployment. The tool exists the moment the code is evaluated, bridging the gap between static API definitions and the dynamic nature of Lisp itself.
This article demonstrates how to build a live Lisp MCP server that writes its own tools at runtime. We will explore the architecture required to handle dynamic tool registration, the specific challenges of integrating this with MCP clients, and how to structure the interaction so the AI can effectively extend the server's capabilities. You will see how to set up a Common Lisp environment that listens for MCP requests while simultaneously accepting code evaluation commands to expand its own toolset. Note that while we use AI for generation, this service is not affiliated with Anthropic, so you are not using their proprietary models or keys.
Frequently asked questions
What is a dynamic MCP server?
A dynamic MCP server is one that can modify its own tool definitions while running. Unlike static servers that list all available tools at startup, a dynamic server can accept instructions to create new tools and install them into its registry immediately. This is particularly powerful in languages like Common Lisp, where code can be evaluated at runtime to add new functions and expose them as new MCP endpoints without restarting the process.
How does a live Lisp server differ from a standard MCP server?
Standard MCP servers have a fixed schema of tools defined in code. A live Lisp server uses the AI to generate tool definitions, which are then evaluated into the running Common Lisp image. This means the server's capabilities are not limited to what was programmed initially; they can expand based on the conversation. The server rewrites itself in real-time, adding new tools as needed for specific coding tasks.
Which is better: static or dynamic MCP servers?
Static servers are simpler and more predictable, making them easier to debug and deploy. However, dynamic servers offer greater flexibility, especially for coding assistants. A static server requires pre-defining every possible tool, while a dynamic server can generate tools on demand. For complex coding tasks where the required tools vary widely, the dynamic approach is often superior because it adapts to the specific context of the code being written.
What is the role of SBCL in this setup?
SBCL (Steel Bank Common Lisp) is the Common Lisp implementation used to run the server. It provides the runtime environment where tools are evaluated. Because SBCL supports dynamic code evaluation, it allows the server to accept new tool definitions from the AI and install them into the running image immediately. This is the core engine that enables the server to rewrite itself without restarting.
How do I handle MCP client connections?
MCP clients connect to the server using standard protocols, typically over JSON-RPC via HTTP or stdio. The server must listen for these connections and process requests according to the MCP specification. When a client requests a list of tools, the server responds with the current set. When a client calls a tool, the server executes the corresponding function. For a dynamic server, the tool list can change dynamically if new tools are added during the session.
What are the limitations of dynamic tool generation?
Dynamic tool generation relies on the AI's ability to produce correct, executable code. If the generated code has errors, the tool may fail or crash the server if not properly isolated. Additionally, the server's memory usage can grow as new tools are added. There is also a risk of state inconsistency if the server's internal state is not carefully managed when tools are added or removed. Proper error handling and sandboxing are essential.
How does this compare to other MCP server implementations?
Other MCP servers, such as those for [Moodle](/moodle-mcp-server) or [Outlook](/outlook-mcp-server), are typically static and tied to specific APIs. They do not modify their own toolset. A live Lisp server is unique in its ability to generate new tools on the fly. This makes it more versatile for coding tasks where the required tools are not known in advance. However, it is also more complex to implement and debug than static servers.
Is this approach suitable for production?
While innovative, a dynamic Lisp server is more suitable for development and experimental use cases. The dynamic nature introduces complexity in terms of state management and error handling. For production environments where reliability and predictability are paramount, static servers are often preferred. However, for coding assistants where adaptability is key, the dynamic approach offers significant advantages in flexibility and responsiveness.
Step by step
- Setup Environment — Install SBCL and Quicklisp. Install necessary libraries like hunchentoot and trivial-json. Configure the HTTP server to listen on a port.
- Define MCP Protocol — Implement the MCP protocol handlers for tool discovery and invocation. Set up the tool registry to store dynamic tools.
- Integrate AI Generator — Connect the server to an AI model. Configure prompts to generate Common Lisp tool definitions. Ensure the AI outputs valid code.
- Evaluate and Register — Receive code from the AI. Validate and evaluate it using eval. Register the new function in the tool registry.
- Test and Optimize — Test the server with MCP clients. Monitor performance and memory usage. Optimize code caching and serialization.
Understanding the MCP Architecture
The Model Context Protocol (MCP) provides a standardized way for AI applications to interact with external data sources and tools. It defines a set of primitives, including resources, prompts, and tools, that clients can discover and invoke. The protocol is designed to be language-agnostic, allowing clients written in any language to communicate with servers implemented in any other. This flexibility is crucial for building diverse ecosystems of AI-powered tools.
MCP servers typically expose a fixed set of tools at startup. When a client connects, it requests the list of available tools and their schemas. The server responds with this list, and the client can then invoke tools by name. This static model works well for predictable interfaces, such as database queries or file operations. However, it lacks the flexibility to adapt to changing requirements during a session, which is where dynamic servers excel.
Tool Registration and Discovery
In a standard MCP server, tools are registered at startup and remain constant. The server maintains a registry of tool names, schemas, and handlers. When a client requests the tool list, the server returns this static registry. This approach is simple and efficient, but it requires pre-defining all possible tools. If a new tool is needed, the server must be restarted or updated with new code.
Dynamic Tool Injection
A dynamic MCP server can add new tools to its registry while running. This is achieved by evaluating new code into the server's environment and registering the new functions as MCP tools. The server updates its tool list in real-time, allowing clients to discover and invoke the new tools immediately. This requires a runtime environment that supports dynamic code evaluation, such as Common Lisp.
# Example of a static MCP tool registration
import mcp
@mcp.tool(name="get_weather")
def get_weather(city: str) -> str:
return f"Weather in {city}: Sunny"
# In a dynamic server, this would be generated and evaluated at runtimeSetting Up the Common Lisp Environment
Common Lisp is chosen for its dynamic nature and powerful macro system, which make it ideal for runtime code generation. SBCL (Steel Bank Common Lisp) is a popular implementation that supports fast compilation and dynamic evaluation. To build a live MCP server, you need a Lisp environment that can run an HTTP server, handle JSON serialization, and evaluate code dynamically.
The first step is to set up a Common Lisp project with the necessary libraries. You will need an HTTP server library to listen for MCP requests, a JSON library for serialization, and an MCP client/server library to handle the protocol. Additionally, you will need a mechanism to evaluate code strings and register new functions as tools. Libraries like `hunchentoot` for HTTP and `closer-mop` for meta-object protocol support are commonly used.
Installing Dependencies
Begin by installing the required Quicklisp libraries. Quicklisp is the standard package manager for Common Lisp. Install `hunchentoot` for the HTTP server, `trivial-json` for JSON handling, and `mcp-server` for the protocol implementation. Ensure that SBCL is installed and configured correctly. These libraries provide the foundation for building the server.
Configuring the HTTP Server
Configure the HTTP server to listen on a specific port and route MCP requests. The server should handle POST requests to the `/mcp` endpoint, parsing the JSON-RPC messages and dispatching them to the appropriate handlers. It should also support the standard MCP endpoints for tool discovery and invocation. Proper error handling is essential to prevent crashes when invalid requests are received.
(ql:quickload '(hunchentoot closer-mop trivial-json))
(defparameter *server* (make-instance 'hunchentoot:easy-acceptor :port 8080))
(defparameter *tool-registry* (make-hash-table))
(defun register-tool (name schema handler)
(setf (gethash name *tool-registry*) (list :schema schema :handler handler)))
Generating Tools with AI
The core innovation of a live Lisp server is its ability to generate new tools using an AI model. The AI analyzes the conversation context and determines what tools would be useful. It then generates a Common Lisp function definition, along with a schema describing the tool's parameters and return type. This code is sent to the server for evaluation.
The AI must produce code that is not only correct but also safe to evaluate. The generated code should not modify global state unpredictably or introduce security vulnerabilities. It should be self-contained and follow the conventions of the MCP protocol. The server then evaluates this code, registering the new function as a tool in its registry. This process can happen multiple times during a session, allowing the server to adapt to changing needs.
AI Prompt Engineering
Design prompts that instruct the AI to generate tool definitions in Common Lisp. Include examples of valid tool schemas and function signatures. Provide clear instructions on how to format the code for evaluation. The prompts should encourage the AI to consider the context of the conversation and generate tools that are relevant to the current task. This requires careful tuning to ensure the generated code is usable.
Code Validation and Safety
Before evaluating the generated code, validate it against a set of safety criteria. Check for syntax errors, ensure that the function signature matches the schema, and verify that the code does not perform dangerous operations. You can use a sandboxed environment to evaluate the code and catch any errors before they affect the main server. This step is crucial for maintaining stability in a dynamic system.
# Example AI-generated tool definition
{
"name": "calculate_fibonacci",
"schema": {
"type": "object",
"properties": {
"n": {"type": "integer"}
}
},
"code": "(defun calculate-fibonacci (n) (if (< n 2) n (+ (calculate-fibonacci (- n 1)) (calculate-fibonacci (- n 2)))))"
}Evaluating Code at Runtime
Evaluating code at runtime is the key to making the server dynamic. In Common Lisp, the `eval` function allows you to execute code strings or forms. The server receives the generated code from the AI, parses it into a Lisp form, and evaluates it. This adds the new function to the server's environment, making it available for immediate use.
The evaluation process must be careful to handle errors gracefully. If the generated code fails to compile or run, the server should log the error and continue operating. It should not crash or become unresponsive. Proper error handling ensures that a single bad tool definition does not disrupt the entire session. The server can also provide feedback to the AI about the success or failure of the evaluation.
The Eval Function
Use the `eval` function to execute the generated code. Pass the code as a Lisp form, not a string, to ensure proper evaluation. The `eval` function returns the result of the code execution, which can be used to verify that the tool was registered correctly. If the evaluation succeeds, the new tool is available in the registry.
Handling Evaluation Errors
Wrap the `eval` call in a `handler-case` to catch any errors. If an error occurs, log it and return an error message to the AI. This allows the AI to correct the code and try again. Error handling is essential for maintaining the stability of a dynamic server, especially when dealing with code generated by an AI.
(handler-case
(eval (read-from-string code-string))
(error (e)
(format t "Evaluation error: ~a" e)
(return-from evaluate-tool nil)))
Integrating with MCP Clients
Once the tools are registered, the server must integrate with MCP clients. Clients discover the available tools by requesting the tool list from the server. The server responds with the current set of tools, including any dynamically added ones. When a client invokes a tool, the server executes the corresponding function and returns the result.
The integration must handle the standard MCP message formats, including `initialize`, `tools/list`, and `tools/call`. The server should also support notifications for tool updates if the client needs to refresh its tool list. This ensures that the client is always aware of the latest capabilities of the server, even if they change during the session.
Tool List Updates
When a new tool is added, the server should notify connected clients. This can be done using MCP notifications or by having the client poll for updates. Notifications are more efficient but require the client to support them. Polling is simpler but adds overhead. Choose the approach that best fits your client's capabilities.
Client Compatibility
Ensure that your server is compatible with standard MCP clients. Test it with popular clients like Claude Desktop or custom implementations. Verify that the tool schemas are correctly formatted and that the tool invocations work as expected. Compatibility testing helps identify any issues with the protocol implementation or the dynamic tool registration process.
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "calculate_fibonacci",
"arguments": {"n": 10}
}
}Managing State and Concurrency
A dynamic server must manage state carefully, especially when multiple clients are connected or when tools are added and removed concurrently. Common Lisp provides robust concurrency features, such as threads and locks, to handle these scenarios. The server should use locks to protect the tool registry and other shared state from race conditions.
State management is crucial for maintaining consistency. If a tool is removed while a client is using it, the server should handle the error gracefully. Similarly, if multiple clients try to add the same tool, the server should ensure that only one instance is registered. Proper state management ensures that the server remains stable and predictable, even in complex scenarios.
Thread Safety
Use locks to protect the tool registry and other shared data structures. Ensure that tool registration and removal are atomic operations. This prevents clients from seeing inconsistent states during updates. Thread safety is essential for multi-client support and concurrent tool modifications.
State Cleanup
Implement mechanisms to clean up state when tools are removed or when clients disconnect. This includes removing tool references, closing connections, and freeing resources. Proper cleanup prevents memory leaks and ensures that the server remains efficient over long sessions.
(defparameter *lock* (bt:make-lock))
(defun register-tool-safe (name schema handler)
(bt:with-lock-held (*lock*)
(setf (gethash name *tool-registry*) (list :schema schema :handler handler)))
Testing and Debugging
Testing a dynamic MCP server requires a different approach than testing static servers. You need to verify that tools are correctly generated, registered, and invoked. Use automated tests to simulate AI-generated code and check that the server responds correctly. Test edge cases, such as invalid code, concurrent updates, and client disconnections.
Debugging dynamic servers can be challenging because the code is changing during runtime. Use logging to track tool registration and invocation. Monitor the server's memory usage and performance to ensure that dynamic code generation does not degrade over time. Debugging tools like SLIME (Superior Lisp Interaction Mode for Emacs) can help you inspect the server's state and trace code execution.
Automated Testing
Write tests that generate tool definitions and verify that they are correctly registered. Test the invocation of these tools to ensure they return the expected results. Use mocking to simulate AI responses and test the server's handling of various code snippets. Automated testing ensures that the server behaves correctly under different conditions.
Logging and Monitoring
Implement comprehensive logging to track tool registration, invocation, and errors. Monitor the server's performance metrics, such as response time and memory usage. This helps identify issues early and ensures that the server remains stable. Logging is essential for debugging dynamic systems where the code is changing.
# Example test case for dynamic tool registration
def test_dynamic_tool_registration():
tool_code = '(defun test-tool () "Hello")'
server.register_tool('test_tool', {}, tool_code)
assert 'test_tool' in server.get_tools()Optimizing Performance
Dynamic code generation can impact performance, especially if the server generates and evaluates many tools. Optimize the evaluation process by caching compiled code where possible. Use efficient data structures for the tool registry and minimize the overhead of JSON serialization. Performance optimization ensures that the server remains responsive, even under heavy load.
Consider the trade-offs between flexibility and performance. A highly dynamic server may be slower than a static one due to the overhead of code evaluation. If performance is critical, you can limit the number of dynamic tools or pre-compile frequently used code. Balancing flexibility and performance is key to building a practical MCP server.
Code Caching
Cache compiled code to avoid re-evaluating the same code multiple times. This reduces the overhead of dynamic code generation and improves response times. Ensure that the cache is invalidated when the code changes. Code caching is a simple but effective way to improve performance in a dynamic server.
Efficient Serialization
Use efficient JSON serialization libraries to minimize the overhead of processing MCP messages. Optimize the tool schema format to reduce the size of the messages. Efficient serialization ensures that the server can handle a high volume of requests without becoming a bottleneck.
(defparameter *code-cache* (make-hash-table))
(defun get-or-eval-code (code-string)
(or (gethash code-string *code-cache*)
(setf (gethash code-string *code-cache*) (eval (read-from-string code-string)))))
Test your first prompt against our free endpoint and see how it compares to the paid API in seconds.