# Directory Structure ``` ├── .gitignore ├── build │ └── main.js ├── CODE_OF_CONDUCT.md ├── LICENSE ├── nodemon.json ├── package-lock.json ├── package.json ├── README.md ├── src │ └── main.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* .pnpm-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # Snowpack dependency directory (https://snowpack.dev/) web_modules/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional stylelint cache .stylelintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variable files .env .env.development.local .env.test.local .env.production.local .env.local # parcel-bundler cache (https://parceljs.org/) .cache .parcel-cache # Next.js build output .next out # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # vuepress v2.x temp and cache directory .temp .cache # vitepress build output **/.vitepress/dist # vitepress cache directory **/.vitepress/cache # Docusaurus cache and generated files .docusaurus # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test # yarn v2 .yarn/cache .yarn/unplugged .yarn/build-state.yml .yarn/install-state.gz .pnp.* ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # three-js-mcp MCP server for controlling ThreeJs source code, only basic function ``` -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- ```markdown # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [email protected]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations ``` -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- ```json { "watch": ["src/**/*.ts"], "ignore": ["src/**/*.spec.ts"], "exec": "npx ts-node ./main.ts" } ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./build", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json { "name": "three-js-mcp", "version": "1.0.0", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "tsc && chmod 755 build/main.js" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@types/express": "^4.17.1", "@types/ws": "^8.18.0", "typescript": "^5.8.2" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.7.0", "express": "^4.17.1", "ws": "^8.18.1" }, "files": [ "build" ] } ``` -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- ```typescript import WebSocket, { WebSocketServer } from 'ws'; import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; // Initialize WebSocket server const wss = new WebSocketServer({ port: 8082 }); let clientConnection: WebSocket | null = null; let sceneState: any = null; wss.on('connection', (ws: WebSocket) => { console.error('Client connected'); clientConnection = ws; ws.on('message', (message: string) => { try { sceneState = JSON.parse(message); console.error('Updated scene state:', sceneState); } catch (e) { console.error('Invalid scene state message:', message); } }); ws.on('close', () => { console.error('Client disconnected'); clientConnection = null; sceneState = null; }); }); // Initialize MCP server const server = new Server( { name: "threejs_mcp_server", version: "1.0.0" }, { capabilities: { prompts: {}, tools: {} } } ); server.onerror = (error) => { console.error("[MCP Error]", error); }; process.on("SIGINT", async () => { wss.close() await server.close(); process.exit(0); }); // Define MCP tools const tools = [ { name: "addObject", description: "Add an object to the scene", inputSchema: { type: "object", properties: { type: { type: "string" }, position: { type: "array", items: { type: "number" }, minItems: 3, maxItems: 3 }, color: { type: "string" } }, required: ["type", "position", "color"] } }, { name: "moveObject", description: "Move an object to a new position", inputSchema: { type: "object", properties: { id: { type: "string" }, position: { type: "array", items: { type: "number" }, minItems: 3, maxItems: 3 } }, required: ["id", "position"] } }, { name: "removeObject", description: "Remove an object", inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } }, { name: "startRotation", description: "Start rotating an object around the y-axis", inputSchema: { type: "object", properties: { id: { type: "string" }, // The ID of the object (e.g., "cube1") speed: { type: "number" } // Rotation speed in radians per frame }, required: ["id", "speed"] } }, { name: "stopRotation", description: "Stop rotating an object", inputSchema: { type: "object", properties: { id: { type: "string" } // The ID of the object }, required: ["id"] } }, { name: "getSceneState", description: "Get the current scene state", inputSchema: { type: "object", properties: {} } } ]; const prompts = [ { name: "asset-creation-strategy", description: "Defines the preferred strategy for creating assets in ThreeJS", arguments: [] } ] // Handle tool listing server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools })); server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts })); // server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: [] })); // Handle tool calls server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: input } = request.params; console.error("request: ===================", request) console.error("state: ===================", sceneState) if (name === "addObject") { if (!clientConnection) { return { content: [ { type: "text", text: "No client connection available" } ] }; } const command = { action: "addObject", ...(input as any) }; clientConnection.send(JSON.stringify(command)); return { content: [ { type: "text", text: "sent" } ] }; } else if (name === "moveObject") { if (!clientConnection) { return { content: [ { type: "text", text: "No client connection available" } ] }; } const command = { action: "moveObject", ...(input as any) }; clientConnection.send(JSON.stringify(command)); return { content: [ { type: "text", text: "sent" } ] }; } else if (name === 'removeObject') { if (!clientConnection) { return { content: [ { type: "text", text: "No client connection available" } ] }; } const command = { action: "removeObject", ...(input as any) }; clientConnection.send(JSON.stringify(command)); return { content: [ { type: "text", text: "sent" } ] }; } else if (name === "getSceneState") { if (sceneState) { return { content: [ { type: "text", text: JSON.stringify(sceneState?.data, null, 2) } ] }; } else { return { content: [ { type: "text", text: "No scene state available" } ] }; } } else if (name === "startRotation") { if (!clientConnection) { return { content: [ { type: "text", text: "No client connection available" } ] }; } const command = { action: "startRotation", id: input?.id, speed: input?.speed }; clientConnection.send(JSON.stringify(command)); return { content: [ { type: "text", text: "sent" } ] }; } else if (name === "stopRotation") { if (!clientConnection) { return { content: [ { type: "text", text: "No client connection available" } ] }; } const command = { action: "stopRotation", id: input?.id }; clientConnection.send(JSON.stringify(command)); return { content: [ { type: "text", text: "sent" } ] }; } return { content: [ { type: "text", text: "Tool not found" } ] };; }); server.setRequestHandler(GetPromptRequestSchema, async (request) => { if (request.params.name !== "asset-creation-strategy") { throw new Error("Unknown prompt"); } return { description: "Defines the preferred strategy for creating assets in ThreeJS", messages: [{ role: "assistant", content: { type: "text", text: ` When creating 3D content in ThreeJS, always start by checking if integrations are available: 0. Before anything, always check the scene from getSceneState() tool 1. Response of getSceneState() tool always give you with the format delimited by ### format ### ### { [ { id: "cube1", type: "cube", position: [0, 0, 0], color: "red", ... } ] } ### 2. Always find the id of the object in response of getSceneState() tool 3. Always use the id of the object to manipulate it with other tools ` } }] }; }); // Start MCP server with stdio transport async function main() { const transport = new StdioServerTransport(); await server.connect(transport); } main().catch((error) => { console.error("Server error:", error); process.exit(1); }); ```