🚀 Magic-API MCP Server
This project integrates the Model Context Protocol (MCP) functionality, offering advanced interaction capabilities for Magic-API development.
🚀 Quick Start
1. Installation and Testing
pip install uv
uv sync
uv add fastmcp
2. MCP Configuration
Basic Configuration (Suitable for Most Users)
{
"mcpServers": {
"magic-api-mcp-server": {
"command": "uvx",
"args": ["magic-api-mcp-server@latest", "--transport", "stdio"],
"timeout": 600
}
}
}
Advanced Configuration (Requires Custom Environment)
{
"mcpServers": {
"magic-api-mcp-server": {
"command": "uvx",
"args": ["magic-api-mcp-server@latest", "--transport", "stdio"],
"timeout": 600,
"env": {
"MAGIC_API_BASE_URL": "http://127.0.0.1:10712",
"MAGIC_API_WS_URL": "ws://127.0.0.1:10712/magic/web/console",
"MAGIC_API_TIMEOUT_SECONDS": "30.0",
"LOG_LEVEL": "INFO"
}
}
}
}
MCP Prompts (Very Important)
Prompt Overview
When using AI assistants that support MCP (such as Claude Desktop, Cursor, etc.), make sure to use the following prompts to let the assistant understand the functions and uses of the Magic-API MCP Server.
Core Prompt
You are now a professional Magic-API developer assistant, equipped with powerful MCP (Model Context Protocol) tool support (Magic-API MCP Server).
## 🎯 Your Core Functions
- Provide guidance on Magic-API script syntax and best practices.
- Assist users in writing efficient database queries and business logic.
- Answer questions related to Magic-API configuration and deployment.
- Offer code examples and debugging suggestions.
## ⚠️ Mandatory Requirement: Obtain Syntax Rules Before Writing Code
**Important**: Before writing any Magic-Script code, you must first call the `get_full_magic_script_syntax` tool to obtain the complete syntax rules.
Magic-Script is a niche language with unique syntax rules and does not follow standard JavaScript or Java syntax.
Writing code without obtaining the complete syntax rules will lead to serious syntax errors.
**Important**: Before writing or editing API scripts (create/edit API scripts), you must:
1. Call `get_full_magic_script_syntax` to obtain the complete Magic-Script syntax rules.
2. Call `get_development_workflow` to obtain the development workflow guide.
3. Follow the standardized development process: Preparation → Information Gathering → Execution → Verification → Summary.
## 🧭 Core Workflow of MagicAPI MCP Agent
> The workflow should be advanced sequentially, and users can instruct to jump at any time.
Call the MCP tools according to the following process to ensure that each step is well-founded:
- **[Requirement Insight]** → `search_knowledge`, `get_development_workflow` to identify the target scenario and constraints.
- **Syntax Alignment** → `get_full_magic_script_syntax`, `get_script_syntax` to confirm the Magic-Script writing method.
- **[Resource Location]** → `get_resource_tree`, `get_api_details_by_path`, `search_api_endpoints` to review existing assets.
- **[Implementation and Debugging]** → `create_api_resource`, `replace_api_script`, `call_magic_api`, `call_api_with_debug`, `set_breakpoint` to implement the code and verify it.
- **[Result Feedback]** → `get_practices_guide`, `get_common_pitfalls`, `list_backups` to output conclusions and ensure traceability.
## 🛠️ Available Tool Capabilities
All available tools are detailed in Section 3 of this document, including:
- **Documentation Tools**: Syntax, documentation, examples, best practices, etc.
- **API Tools**: Interface invocation and testing.
- **Resource Management Tools**: CRUD operations on resources.
- **Query Tools**: Resource retrieval.
- **Debug Tools**: Breakpoint management.
- **Search Tools**: Content search.
- **Backup Tools**: Data backup management.
- **Class Method Tools**: Java class and method query.
- **System Tools**: System metadata query.
For details, please refer to Section 3 "MCP Tool Functions of This Project" below.
## 📋 Usage Guide
##### Problem Analysis
First, understand the user's requirements and context, and then select the appropriate tool.
##### Knowledge Search Strategy
🔍 **When you are unsure about a certain function or syntax, give priority to using the search tool**:
- Call `search_knowledge` for a full-text search. The keywords can be function names, syntax keywords, etc.
- For example, search for "database connection", "cache usage", "file upload", etc.
- You can limit the search category: syntax, modules, functions, web_docs, etc.
##### Best Practices
- 🔍 **When encountering uncertain problems, search the knowledge base first**.
- 📚 Give priority to using the documentation query tool to understand functions.
- 🔍 Use the query tool to understand existing resources during development.
- 🐛 Set breakpoints to troubleshoot problems step by step during debugging.
- 💾 Back up before important change operations.
##### Error Handling
- 🔍 When encountering unknown errors, use `search_knowledge` to search for relevant solutions.
- 🌐 Check the Magic-API service status in case of network errors.
- 🔐 Confirm the user authentication configuration in case of permission errors.
- 📁 Use the query tool to confirm the path when the resource does not exist.
Short Prompt (Suitable for Quick Configuration)
You are a professional Magic-API developer assistant with the following MCP tools:
⚠️ Mandatory Requirement:
- You must call `get_full_magic_script_syntax` to obtain the complete syntax rules before writing any Magic-Script code!
- You must call `get_development_workflow` to obtain the workflow guide before writing or editing API scripts (create/edit API scripts)!
📚 Documentation Query: `get_full_magic_script_syntax` [Mandatory], `get_development_workflow` [Mandatory], `search_knowledge` [Recommended], `get_script_syntax`, `get_module_api`, `get_best_practices`, `get_examples`
🔧 API Invocation: `call_magic_api`
📁 Resource Management: `get_resource_tree`, `create_api_resource`, `delete_resource`
🔍 Query Tools: `get_api_details_by_path`, `get_api_details_by_id`, `search_api_endpoints`
🐛 Debug Tools: `set_breakpoint`, `resume_breakpoint_execution`, `call_api_with_debug`
🔎 Search Tools: `search_api_scripts`, `search_todo_comments`
💾 Backup Tools: `list_backups`, `create_full_backup`, `rollback_backup`
⚙️ System Tools: `get_assistant_metadata`
🔍 Give priority to using `search_knowledge` to search the knowledge base when unsure, and obtain the complete syntax rules before writing code.
🧭 Complete the requirement insight → syntax alignment → resource location → implementation and debugging → result feedback in the order of the core workflow.
Configuration Prompt (For Editors like Cursor/VS Code)
{
"mcpServers": {
"magic-api-mcp-server": {
"command": "uvx",
"args": ["magic-api-mcp-server@latest", "--transport", "stdio"],
"timeout": 600,
"env": {
"MAGIC_API_BASE_URL": "http://127.0.0.1:10712",
"MAGIC_API_WS_URL": "ws://127.0.0.1:10712/magic/web/console"
}
}
}
}
The MCP server of this project is specifically designed for Magic-API developers, providing a complete set of workflow tools to comprehensively improve development efficiency from script writing, API management to debugging and deployment.
🧠 Prompts (Prompt Templates)
The Magic-API MCP Server provides reusable prompt templates to help you quickly configure a professional Magic-API developer assistant.
Available Prompts
magic_api_developer_guide
Generate a professional Magic-API developer assistant prompt, including:
- A complete introduction to tool capabilities.
- Usage guides and best practices.
- Error handling suggestions.
- Tool selection strategies.
Usage Method:
prompt = await client.get_prompt("magic_api_developer_guide")
content = prompt.messages[0].content.text
Applicable Scenarios:
- Configure a new AI assistant.
- Standardize the development workflow.
- Train new team members.
- Create a consistent development environment.
Tool Combination Configuration
This project supports various tool combinations, which can be selected according to your needs:
full: Complete toolset - suitable for a full development environment (default).
minimal: Minimal toolset - suitable for resource-constrained environments.
development: Development toolset - focused on development and debugging.
production: Production toolset - for stable operation in the production environment.
documentation_only: Documentation-only toolset - for document query and learning.
api_only: API-only toolset - for interface testing and invocation.
backup_only: Backup-only toolset - for data backup and management.
class_method_only: Class-method-only toolset - for Java class and method query.
search_only: Search-only toolset - for quick search and location.
Tool Combination Usage Scenarios:
| Scenario |
Combination Mode |
Applicable Environment |
Features |
| Newcomer Learning |
documentation_only |
Learning Phase |
Focus on document query and syntax learning |
| API Development |
development |
Development Environment |
Interface development, testing, and debugging |
| Production Operation and Maintenance |
production |
Production Environment |
System operation and maintenance and resource management |
| Problem Debugging |
minimal |
Debugging Scenario |
Problem troubleshooting, enable DEBUG logs |
Basic Configuration Template:
{
"mcpServers": {
"magic-api-server": {
"command": "uvx",
"args": ["magic-api-mcp-server@latest", "--composition", "{combination mode}", "--transport", "stdio"],
"timeout": 600
}
}
}
3. MCP Tool Functions of This Project
The Magic-API MCP Server provides the following professional tools for Magic-API development:
3.1 System Tools (SystemTools)
System information and metadata tools
- get_assistant_metadata: Obtain the complete metadata of the Magic-API MCP Server, including version, function list, and configuration.
3.2 Documentation Tools (DocumentationTools)
Document query and knowledge base tools, covering syntax, practices, examples, and processes
- get_full_magic_script_syntax ⚠️ [Mandatory]: Obtain the complete Magic-Script syntax rules - this tool must be called before the large model writes code.
- search_knowledge 🔍 [Recommended]: Conduct a full-text search in the Magic-API knowledge base - give priority to using this tool when unsure.
- get_magic_script_syntax: Query the Magic-Script syntax rules and examples.
- get_magic_script_examples: Obtain script examples, supporting keyword filtering.
- get_magic_api_docs: View the official document index or detailed content.
- get_best_practices: Consult the list of best practices.
- get_common_pitfalls: Consult common problems and avoidance suggestions.
- get_development_workflow: Obtain the standardized development process guide.
- get_module_api_docs: Query the API documentation of built-in modules.
- list_available_modules: View available modules and automatically imported modules.
- get_function_docs: Obtain the documentation of the built-in function library.
- get_extension_docs: Obtain the documentation of type extensions (disabled by default, available after enabling).
- get_config_docs: Obtain the documentation of configuration items (disabled by default).
- get_plugin_docs: Obtain the documentation of the plugin system (disabled by default).
- get_examples / list_examples: Uniformly query example classifications and code snippets.
- get_docs: Obtain the index of the Magic-API official website.
3.3 API Tools (ApiTools)
API invocation and testing tools, supporting flexible interface invocation and testing
- call_magic_api: Invoke the Magic-API interface and return the request result, supporting HTTP methods such as GET, POST, PUT, DELETE.
🔍 Intelligent API Response Check
The Magic-API MCP Server supports intelligent success/failure judgment for various API response formats:
Priority Order:
- 🚀
message="success" - Highest priority, directly match whether the message field is equal to "success".
- 🔢 Code Field Check - Check whether the code field is equal to the configured success code (default is 1, configurable).
- 📊 Status Field Check - Check the status field (some custom response formats).
- ❌ Error Field Check - Check whether there are error fields such as error, exception, failure.
- ✅ Default Success - Compatibility mode, responses without clear identification are considered successful by default.
Examples of Supported Response Formats:
{"code": 1, "message": "success", "data": {...}}
{"code": 200, "message": "ok", "data": {...}}
{"code": 500, "message": "success", "data": {...}}
{"code": 1, "message": "operation failed", "data": {...}}
{"status": 1, "msg": "success", "body": {...}}
{"code": 500, "message": "Internal Error", "data": {...}}
{"error": "something went wrong"}
Configuration Method:
MAGIC_API_SUCCESS_CODE=200
MAGIC_API_SUCCESS_MESSAGE=ok
MAGIC_API_INVALID_CODE=400
MAGIC_API_EXCEPTION_CODE=500
3.4 Resource Management Tools (ResourceManagementTools)
A complete resource management system, supporting resource tree query and batch operations
- get_resource_tree: Obtain the resource tree, supporting filtering and exporting in various formats (JSON/CSV/tree), backward compatible with CSV parameters.
- save_group: Save a group, supporting the creation or update of a single group, including complete group configuration options.
- create_api_resource / create_api_endpoint: Create single or batch APIs.
- replace_api_script: Replace the Magic-Script snippet by interface ID, supporting single or full replacement.
- copy_resource: Copy resources.
- move_resource: Move resources.
- delete_resource: Delete single or batch resources.
- lock_resource / unlock_resource: Batch lock or unlock resources.
- list_resource_groups: List and search resource groups.
- get_resource_stats: Statistically analyze the number and type distribution of resources.
3.5 Query Tools (QueryTools)
Efficient resource query and retrieval tools
- get_api_details_by_path: Directly obtain the detailed information of an interface according to the API path, supporting fuzzy matching.
- get_api_details_by_id: Obtain the complete detailed information and configuration of an interface according to the interface ID.
- search_api_endpoints: Search and filter Magic-API interface endpoints, returning a complete information list including IDs.
3.6 Debug Tools (DebugTools)
Powerful debugging functions, supporting breakpoint management and debugging sessions
- set_breakpoint: Set a breakpoint in the specified API script.
- remove_breakpoint: Remove the specified breakpoint.
- resume_breakpoint_execution: Resume breakpoint execution and continue running the debugging script.
- step_over_breakpoint: Step over the current breakpoint and continue execution.
- list_breakpoints: List all currently set breakpoints.
- call_api_with_debug: Invoke the specified interface and pause when the breakpoint is hit.
- execute_debug_session: Execute a complete debugging session.
- get_debug_status: Obtain the current debugging status.
- clear_all_breakpoints: Clear all breakpoints.
- get_websocket_status: Obtain the WebSocket connection status.
3.7 Search Tools (SearchTools)
Content search and location
- search_api_scripts: Retrieve keywords in all API scripts.
- search_todo_comments: Search for TODO comments in scripts (disabled by default).
3.8 Backup Tools (BackupTools)
Complete backup management functions
- list_backups: Query the backup list, supporting timestamp filtering and name filtering.
- get_backup_history: Obtain the backup history.
- get_backup_content: Obtain the content of the specified backup.
- rollback_backup: Roll back to the specified backup version.
- create_full_backup: Create a complete system backup.
3.9 Class Method Tools (ClassMethodTools)
Java class and method retrieval tools
- list_magic_api_classes: List all available Magic-API classes, extensions, and functions, supporting paged browsing.
- get_class_details: Obtain the detailed information of the specified class, including methods, attributes, and inheritance relationships.
- get_method_details: Obtain the detailed information of the specified method, including parameter types and return values.
3.10 Code Generation Tools (CodeGenerationTools) - Currently Disabled
Intelligent code generation functions (need to be enabled for use)
- generate_crud_api: Generate complete CRUD API interface code.
- generate_database_query: Generate database query code.
- generate_api_test: Generate API interface test code.
- generate_workflow_code: Generate workflow template code.
3.11 Prompt Tools (PromptTools)
Provide reusable prompt templates to ensure that the assistant strictly follows the MCP tooling process
- magic_api_developer_guide: Output the latest version of the "Magic-API Developer Assistant" system prompt, emphasizing the work rule of "relying only on MCP tools", the six-step tool workflow, and the requirements for structured output.
3.12 Highlights of the Workflow Knowledge Base
New workflows such as "mcp_tool_driven" have been added to magicapi_tools/utils/kb_practices.py. You can obtain them by calling get_development_workflow or get_practices_guide:
- 🔍 Intelligent Search Driven: When encountering uncertain problems, give priority to calling the
search_knowledge tool to conduct a full-text search of the knowledge base to ensure that the latest and accurate information is obtained.
- General process prioritizing MCP tools: Covers the entire link of preparation, information collection, execution, verification, and summary, and provides corresponding tool prompts for each step.
- Scenario-based processes such as api_script_development / diagnose / optimize / refactor: Provide principle explanations, step breakdowns, and tool lists to ensure that the entire process of interface development, fault troubleshooting, performance optimization, and refactoring relies on MCP tools.
- Combined with the
magic_api_developer_guide prompt, the large model can actively reference tool evidence in the dialogue and output verifiable conclusions.
4. Environment Variables
| Property |
Details |
Value |
Default |
| MAGIC_API_BASE_URL |
Magic-API service base URL |
URL address |
http://127.0.0.1:10712 |
| MAGIC_API_WS_URL |
Magic-API WebSocket URL |
WebSocket address |
ws://127.0.0.1:10712/magic/web/console |
| MAGIC_API_USERNAME |
Magic-API authentication username |
String |
None |
| MAGIC_API_PASSWORD |
Magic-API authentication password |
String |
None |
| MAGIC_API_TOKEN |
Magic-API authentication token |
String |
None |
| MAGIC_API_AUTH_ENABLED |
Whether to enable authentication |
true/false |
false |
| MAGIC_API_TIMEOUT_SECONDS |
Request timeout in seconds |
Number |
30.0 |
| MAGIC_API_SUCCESS_CODE |
API success status code |
Number |
1 |
| MAGIC_API_SUCCESS_MESSAGE |
API success message text |
String |
success |
| MAGIC_API_INVALID_CODE |
Parameter validation failure status code |
Number |
0 |
| MAGIC_API_EXCEPTION_CODE |
System exception status code |
Number |
-1 |
| LOG_LEVEL |
Log level |
DEBUG/INFO/WARNING/ERROR |
INFO |
| FASTMCP_TRANSPORT |
FastMCP transport protocol |
stdio/http |
stdio |
5. Local Running Method
uvx magic-api-mcp-server@latest
magic-api-mcp-server
uv run fastmcp run run_mcp.py:mcp --transport http --port 8000
uvx magic-api-mcp-server@latest --composition development
MAGIC_API_BASE_URL=http://localhost:8080 uvx magic-api-mcp-server@latest
6. Docker Running Method
Use Docker Compose (Recommended)
make quick-start
make deploy
make logs
make status
make shell
make test
docker-compose up -d
docker-compose logs -f magic-api-mcp-server
docker-compose down
docker-compose restart magic-api-mcp-server
Use Docker Commands (Based on uvx)
docker build -t magic-api-mcp-server .
docker run --rm --entrypoint uvx magic-api-mcp-server \
magic-api-mcp-server@latest --composition full --transport stdio
docker run -d --name magic-api-mcp-server \
-p 8000:8000 \
--entrypoint uvx magic-api-mcp-server \
magic-api-mcp-server@latest --transport http --port 8000
docker logs -f magic-api-mcp-server
docker stop magic-api-mcp-server
Docker Configuration Instructions
Advantages of Using uvx:
- Automatically download and run the latest version of the package.
- No need to pre-install dependencies.
- Smaller image size and faster build speed.
- Automatically handle package version management.
Production Environment Configuration (docker-compose.yml):
- Connect to the Magic-API service using a bridged network.
- Configure resource limits and health checks.
- Support automatic restart.
Development Environment Configuration (docker-compose.override.yml):
- Mount the source code to support hot reloading.
- Set the debug log level.
- Disable health checks.
Docker Environment Variables
| Property |
Details |
Default |
MAGIC_API_BASE_URL |
Magic-API service base URL |
http://host.docker.internal:10712 |
MAGIC_API_WS_URL |
Magic-API WebSocket URL |
ws://host.docker.internal:10712/magic/web/console |
MAGIC_API_USERNAME |
Authentication username |
None |
MAGIC_API_PASSWORD |
Authentication password |
None |
MAGIC_API_TOKEN |
Authentication token |
None |
MAGIC_API_AUTH_ENABLED |
Whether to enable authentication |
false |
MAGIC_API_TIMEOUT_SECONDS |
Request timeout |
30.0 |
MAGIC_API_SUCCESS_CODE |
API success status code |
1 |
MAGIC_API_SUCCESS_MESSAGE |
API success message text |
success |
MAGIC_API_INVALID_CODE |
Parameter validation failure status code |
0 |
MAGIC_API_EXCEPTION_CODE |
System exception status code |
-1 |
LOG_LEVEL |
Log level |
INFO |
FASTMCP_TRANSPORT |
MCP transport protocol |
stdio |
Network Configuration Notes
- Linux: Use
host.docker.internal to access the host service.
- macOS/Windows: Docker Desktop automatically provides
host.docker.internal.
- Custom Network: You can create a dedicated network using
docker network.
Solutions to Docker Build Problems
If you encounter network certificate verification issues, try the following solutions:
Solution 1: Use a domestic mirror source
RUN sed -i 's/deb.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list.d/debian.sources
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple/
Solution 2: Configure the Docker proxy
{
"proxies": {
"default": {
"httpProxy": "http://127.0.0.1:7897",
"httpsProxy": "http://127.0.0.1:7897",
"noProxy": "localhost,127.0.0.1"
}
}
}
Solution 3: Skip TLS verification (for testing only)
docker build --build-arg DOCKER_TLS_VERIFY=0 -t magic-api-mcp-server:test .
Solution 4: Use a pre-built image
Troubleshooting
make status
make shell
make logs-tail
make test
make test-connection
make clean-all
docker-compose ps
docker-compose exec magic-api-mcp-server bash
docker-compose logs --tail=100 magic-api-mcp-server
docker-compose down --rmi all --volumes
7. Project Structure
magicapi_mcp/
├── magicapi_assistant.py # Main MCP assistant implementation
├── tool_registry.py # Tool registry
├── tool_composer.py # Tool combiner
└── settings.py # Configuration settings
magicapi_tools/
├── tools/ # Various MCP tools
│ ├── system.py # System tools (metadata query)
│ ├── documentation.py # Documentation tools (knowledge base query)
│ ├── api.py # API tools (interface invocation)
│ ├── resource.py # Resource management tools (CRUD operations)
│ ├── query.py # Query tools (resource retrieval)
│ ├── debug.py # Debug tools (breakpoint management)
│ ├── search.py # Search tools (content search)
│ ├── backup.py # Backup tools (data backup)
│ ├── class_method.py # Class method tools (Java class query)
│ ├── code_generation.py # Code generation tools (currently disabled)
│ └── common.py # Common helper functions
└── utils/ # Tool assistant functions
├── knowledge_base.py # Knowledge base interface
├── response.py # Standardized response
├── http_client.py # HTTP client
└── resource_manager.py # Resource manager
8. Installation Methods
Install from PyPI (Recommended)
pip install magic-api-mcp-server
uv add magic-api-mcp-server
uvx magic-api-mcp-server@latest
magic-api-mcp-server
Local Installation for Developers
cd magic-api-mcp-server
uv sync
uv add fastmcp
python run_mcp.py