chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
OPENAI_API_KEY=your-openai-api-key-here
|
||||
|
||||
# Optional: enable CopilotKit Intelligence Threads locally
|
||||
COPILOTKIT_LICENSE_TOKEN=
|
||||
INTELLIGENCE_API_KEY=
|
||||
INTELLIGENCE_API_URL=http://localhost:4201
|
||||
INTELLIGENCE_GATEWAY_WS_URL=ws://localhost:4401
|
||||
@@ -0,0 +1,48 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
!.env.example
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
|
||||
ext-apps
|
||||
|
||||
# LangGraph API
|
||||
.langgraph_api
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) Atai Barkai
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,110 @@
|
||||
# CopilotKit <> MCP Apps Starter
|
||||
|
||||
This is a starter template for integrating [MCP Apps](https://mcpui.dev) with [CopilotKit](https://copilotkit.ai). It uses the [Three.js example](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/threejs-server) from the official Model Context Protocol organization on GitHub.
|
||||
|
||||
https://github.com/user-attachments/assets/8908af31-2b64-4426-9c83-c51ab86256de
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
.
|
||||
├── app/ # Next.js App Router pages and API routes
|
||||
│ ├── page.tsx # Main page
|
||||
│ └── api/copilotkit/ # CopilotKit API route
|
||||
├── threejs-server/ # MCP App Server (Three.js)
|
||||
│ ├── server.ts # Server entry point
|
||||
│ ├── src/ # Three.js app source
|
||||
│ └── package.json
|
||||
├── scripts/ # MCP server run scripts
|
||||
├── next.config.ts
|
||||
├── tsconfig.json
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 20+
|
||||
- Any of the following package managers:
|
||||
- npm (default)
|
||||
- [pnpm](https://pnpm.io/installation)
|
||||
- [yarn](https://classic.yarnpkg.com/lang/en/docs/install/)
|
||||
- [bun](https://bun.sh/)
|
||||
- OpenAI API Key
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Install dependencies using your preferred package manager:
|
||||
|
||||
```bash
|
||||
# Using npm (default)
|
||||
npm install
|
||||
|
||||
# Using pnpm
|
||||
pnpm install
|
||||
|
||||
# Using yarn
|
||||
yarn install
|
||||
|
||||
# Using bun
|
||||
bun install
|
||||
```
|
||||
|
||||
> The `postinstall` script automatically installs the MCP server dependencies in `threejs-server/`.
|
||||
|
||||
2. Set up your environment variables:
|
||||
|
||||
```bash
|
||||
echo 'OPENAI_API_KEY=your-openai-api-key-here' > .env
|
||||
```
|
||||
|
||||
3. Start the development servers:
|
||||
|
||||
```bash
|
||||
# Using npm (default)
|
||||
npm run dev
|
||||
|
||||
# Using pnpm
|
||||
pnpm dev
|
||||
|
||||
# Using yarn
|
||||
yarn dev
|
||||
|
||||
# Using bun
|
||||
bun run dev
|
||||
```
|
||||
|
||||
This starts both the Next.js app and the MCP server concurrently.
|
||||
|
||||
## Available Scripts
|
||||
|
||||
The following scripts can also be run using your preferred package manager:
|
||||
|
||||
- `dev` - Starts both the UI and MCP server in development mode
|
||||
- `dev:ui` - Starts only the Next.js UI server
|
||||
- `dev:mcp` - Starts only the MCP App Server
|
||||
- `build` - Builds the Next.js application for production
|
||||
- `start` - Starts the production server
|
||||
|
||||
## Customization
|
||||
|
||||
The main UI component is in `app/page.tsx`. You can:
|
||||
|
||||
- Modify the theme colors and styling
|
||||
- Add new frontend actions
|
||||
- Customize the CopilotKit sidebar appearance
|
||||
|
||||
The MCP App Server code is in `threejs-server/`.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [CopilotKit Documentation](https://docs.copilotkit.ai) - Explore CopilotKit's capabilities
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - Learn about Next.js features and API
|
||||
- [MCP Apps Documentation](https://mcpui.dev/guide/introduction) - Learn more about MCP Apps and how to use it
|
||||
|
||||
## Contributing
|
||||
|
||||
Feel free to submit issues and enhancement requests! This starter is designed to be easily extensible.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see the LICENSE file for details.
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
CopilotKitIntelligence,
|
||||
CopilotRuntime,
|
||||
InMemoryAgentRunner,
|
||||
createCopilotEndpoint,
|
||||
} from "@copilotkit/runtime/v2";
|
||||
import { BuiltInAgent } from "@copilotkit/runtime/v2";
|
||||
import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";
|
||||
import { handle } from "hono/vercel";
|
||||
|
||||
const middlewares = [
|
||||
new MCPAppsMiddleware({
|
||||
mcpServers: [
|
||||
{
|
||||
type: "http",
|
||||
url: "http://localhost:3108/mcp",
|
||||
serverId: "threejs",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const agent = new BuiltInAgent({
|
||||
model: "openai/gpt-4o",
|
||||
prompt: "You are a helpful assistant.",
|
||||
});
|
||||
|
||||
for (const middleware of middlewares) {
|
||||
agent.use(middleware);
|
||||
}
|
||||
|
||||
const runtime = new CopilotRuntime({
|
||||
agents: {
|
||||
default: agent,
|
||||
},
|
||||
// --- copilotkit:intelligence (remove this block to opt out) ---
|
||||
...(process.env.COPILOTKIT_LICENSE_TOKEN
|
||||
? {
|
||||
intelligence: new CopilotKitIntelligence({
|
||||
apiKey: process.env.INTELLIGENCE_API_KEY ?? "",
|
||||
apiUrl: process.env.INTELLIGENCE_API_URL ?? "http://localhost:4201",
|
||||
wsUrl:
|
||||
process.env.INTELLIGENCE_GATEWAY_WS_URL ?? "ws://localhost:4401",
|
||||
}),
|
||||
// Demo stub — replace with your own auth-derived user identity (e.g. OIDC)
|
||||
// before any multi-user deployment, or all users share one thread history.
|
||||
identifyUser: () => ({ id: "demo-user", name: "Demo User" }),
|
||||
licenseToken: process.env.COPILOTKIT_LICENSE_TOKEN,
|
||||
}
|
||||
: { runner: new InMemoryAgentRunner() }),
|
||||
// --- /copilotkit:intelligence ---
|
||||
});
|
||||
|
||||
const app = createCopilotEndpoint({
|
||||
runtime,
|
||||
basePath: "/api/copilotkit",
|
||||
});
|
||||
|
||||
export const GET = handle(app);
|
||||
export const POST = handle(app);
|
||||
export const PATCH = handle(app);
|
||||
export const DELETE = handle(app);
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,55 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.985 0 0);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
|
||||
--radius: 0.625rem;
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
|
||||
--font-body: Arial, Helvetica, sans-serif;
|
||||
--font-code: "SFMono-Regular", Menlo, monospace;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
.threadsLayout,
|
||||
body > [role="presentation"] {
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--background: oklch(1 0 0);
|
||||
}
|
||||
|
||||
body,
|
||||
html {
|
||||
height: 100%;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { CopilotKit } from "@copilotkit/react-core";
|
||||
import "./globals.css";
|
||||
import "@copilotkit/react-ui/v2/styles.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className={"antialiased"}>
|
||||
<CopilotKit
|
||||
runtimeUrl="/api/copilotkit"
|
||||
showDevConsole={false}
|
||||
useSingleEndpoint={false}
|
||||
>
|
||||
{children}
|
||||
</CopilotKit>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
.layout {
|
||||
display: grid;
|
||||
/*
|
||||
Reserve the desktop drawer's width (its default 320px) as a fixed first
|
||||
column so the layout doesn't shift when the client-only <CopilotThreadsDrawer>
|
||||
mounts after hydration. On mobile the drawer is an off-canvas overlay (out
|
||||
of flow), so the column collapses and the content fills the width.
|
||||
*/
|
||||
grid-template-columns: var(--cpk-drawer-reserved-width, 320px) minmax(0, 1fr);
|
||||
/* Drawer sets --cpk-drawer-reserved-width to 0 on desktop-collapse, so the
|
||||
reserved column collapses and the chat reclaims the space. */
|
||||
transition: grid-template-columns 0.2s ease;
|
||||
/*
|
||||
Bound the single grid row to the viewport (minmax(0,1fr) lets it shrink
|
||||
below content) so a long thread list scrolls INTERNALLY in the drawer with
|
||||
the header pinned, instead of the drawer growing past the viewport and the
|
||||
page scrolling the header away.
|
||||
*/
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
height: 100dvh;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
|
||||
/*
|
||||
Paint the surface light. globals.css flips the root `--background` to
|
||||
#0a0a0a under prefers-color-scheme: dark, and `.threadsLayout` (combined on
|
||||
this element) only re-pins the *variable* light without painting it — so the
|
||||
empty area around the centered chat showed the dark body through. The drawer
|
||||
and CopilotChat render light here, so paint the whole surface from the
|
||||
pinned light `--background` to match.
|
||||
*/
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
.mainPanel {
|
||||
/*
|
||||
Pin the content to the SECOND track explicitly. The client-only drawer
|
||||
renders nothing during SSR, so without this the content would flow into the
|
||||
reserved first column at first paint and then jump once the drawer mounts.
|
||||
*/
|
||||
grid-column: 2;
|
||||
min-width: 0;
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/*
|
||||
Mobile (≤768px): the drawer is an off-canvas overlay — collapse to a single
|
||||
track. MUST come after the base rules (media queries add no specificity, so a
|
||||
later same-specificity base rule would otherwise win and leak the two-column
|
||||
desktop layout onto mobile).
|
||||
*/
|
||||
@media (max-width: 768px) {
|
||||
.layout {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.mainPanel {
|
||||
grid-column: auto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CopilotChat,
|
||||
CopilotChatConfigurationProvider,
|
||||
CopilotThreadsDrawer,
|
||||
} from "@copilotkit/react-core/v2";
|
||||
|
||||
import styles from "./page.module.css";
|
||||
|
||||
const agentId = "default";
|
||||
|
||||
export default function CopilotKitPage() {
|
||||
return (
|
||||
/*
|
||||
One UNCONTROLLED CopilotChatConfigurationProvider (no `threadId` prop) owns
|
||||
the active thread for the whole surface. The SDK <CopilotThreadsDrawer> drives it
|
||||
directly — picking a row sets the active thread, "+ New" resets to a fresh
|
||||
thread (clearing the chat) — with no host thread-state. The chat reads the
|
||||
same active thread from the provider. A *controlled* provider would block
|
||||
"+ New" from resetting, so uncontrolled-inside-provider is required.
|
||||
*/
|
||||
<CopilotChatConfigurationProvider agentId={agentId}>
|
||||
<div className={`${styles.layout} threadsLayout`}>
|
||||
{/* SDK threads drawer (replaces the hand-rolled fork). License-gated: the locked view's Upgrade CTA opens the Intelligence docs by default. */}
|
||||
<CopilotThreadsDrawer agentId={agentId} />
|
||||
<div className={styles.mainPanel}>
|
||||
<main className="h-full w-full flex justify-center items-center">
|
||||
<CopilotChat
|
||||
agentId={agentId}
|
||||
className="w-full max-w-3xl h-full"
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</CopilotChatConfigurationProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
serverExternalPackages: ["@copilotkit/runtime"],
|
||||
env: {
|
||||
NEXT_PUBLIC_COPILOTKIT_THREADS_ENABLED: process.env.COPILOTKIT_LICENSE_TOKEN
|
||||
? "true"
|
||||
: "false",
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
+12716
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "mcp-apps-starter",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently \"npm run dev:ui\" \"npm run dev:mcp\" --names ui,mcp --prefix-colors blue,green --kill-others",
|
||||
"dev:ui": "next dev --turbopack",
|
||||
"dev:mcp": "./scripts/run-mcp-server.sh || scripts\\run-mcp-server.bat",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"install:mcp": "cd threejs-server && npm install",
|
||||
"postinstall": "npm run install:mcp"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ag-ui/client": "0.0.57",
|
||||
"@ag-ui/mcp-apps-middleware": "^0.0.3",
|
||||
"@copilotkit/react-core": "1.62.3",
|
||||
"@copilotkit/react-ui": "1.62.3",
|
||||
"@copilotkit/runtime": "1.62.3",
|
||||
"hono": "^4.12.10",
|
||||
"lucide-react": "^0.561.0",
|
||||
"next": "16.1.1",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"concurrently": "^9.1.2",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
const config = {
|
||||
plugins: ["@tailwindcss/postcss"],
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0..\threejs-server"
|
||||
npm run dev
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
cd "$(dirname "$0")/../threejs-server" || exit 1
|
||||
npm run dev
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -0,0 +1,110 @@
|
||||
# Example: Three.js App
|
||||
|
||||

|
||||
|
||||
Interactive 3D scene renderer using Three.js. Demonstrates streaming code preview and full MCP App integration.
|
||||
|
||||
## Features
|
||||
|
||||
- **Interactive 3D Rendering**: Execute JavaScript code to create and animate Three.js scenes
|
||||
- **Streaming Preview**: See the scene build in real-time as code is being written
|
||||
- **Built-in Helpers**: Pre-configured `OrbitControls`, post-processing effects (bloom), and render passes
|
||||
- **Documentation Tool**: `learn_threejs` provides API docs and code examples on demand
|
||||
|
||||
## Running
|
||||
|
||||
1. Install dependencies:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. Build and start the server:
|
||||
|
||||
```bash
|
||||
npm run start:http # for Streamable HTTP transport
|
||||
# OR
|
||||
npm run start:stdio # for stdio transport
|
||||
```
|
||||
|
||||
3. View using the [`basic-host`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-host) example or another MCP Apps-compatible host.
|
||||
|
||||
### Tool Input
|
||||
|
||||
To test the example, copy the contents of [`test-input.json`](test-input.json) into the tool input field in `basic-host`.
|
||||
|
||||
The test input creates a simple scene with a rotating cube:
|
||||
|
||||
```javascript
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 100);
|
||||
camera.position.set(2, 2, 2);
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
|
||||
renderer.setSize(width, height);
|
||||
renderer.shadowMap.enabled = true;
|
||||
|
||||
const cube = new THREE.Mesh(
|
||||
new THREE.BoxGeometry(),
|
||||
new THREE.MeshStandardMaterial({ color: 0x00ff88 }),
|
||||
);
|
||||
cube.castShadow = true;
|
||||
cube.position.y = 0.5;
|
||||
scene.add(cube);
|
||||
|
||||
const floor = new THREE.Mesh(
|
||||
new THREE.PlaneGeometry(5, 5),
|
||||
new THREE.MeshStandardMaterial({ color: 0x222233 }),
|
||||
);
|
||||
floor.rotation.x = -Math.PI / 2;
|
||||
floor.receiveShadow = true;
|
||||
scene.add(floor);
|
||||
|
||||
const light = new THREE.DirectionalLight(0xffffff, 2);
|
||||
light.position.set(3, 5, 3);
|
||||
light.castShadow = true;
|
||||
scene.add(light);
|
||||
scene.add(new THREE.AmbientLight(0x404040));
|
||||
|
||||
function animate() {
|
||||
requestAnimationFrame(animate);
|
||||
cube.rotation.y += 0.01;
|
||||
renderer.render(scene, camera);
|
||||
}
|
||||
animate();
|
||||
```
|
||||
|
||||
#### Available Three.js Globals
|
||||
|
||||
When writing custom code, these globals are available:
|
||||
|
||||
```javascript
|
||||
THREE; // Three.js library
|
||||
canvas; // Pre-created canvas element
|
||||
width; // Canvas width
|
||||
height; // Canvas height
|
||||
OrbitControls; // Camera controls
|
||||
EffectComposer; // Post-processing composer
|
||||
RenderPass; // Render pass
|
||||
UnrealBloomPass; // Bloom effect
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Server (`server.ts`)
|
||||
|
||||
Exposes two tools:
|
||||
|
||||
- `show_threejs_scene` - Renders a 3D scene from JavaScript code
|
||||
- `learn_threejs` - Returns documentation and code examples for Three.js APIs
|
||||
|
||||
Supports Streamable HTTP and stdio transports.
|
||||
|
||||
### App (`src/threejs-app.tsx`)
|
||||
|
||||
React component that:
|
||||
|
||||
- Receives tool inputs via the MCP App SDK
|
||||
- Displays streaming preview from `toolInputsPartial.code` as code arrives
|
||||
- Executes final code from `toolInputs.code` when complete
|
||||
- Renders to a pre-created canvas with configurable height
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:9068f44bf72e5b5c69d61cf86d5f7f0e00c38689acd151960a2269444ea6bfe3
|
||||
size 4857
|
||||
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>Three.js Widget</title>
|
||||
<link rel="stylesheet" href="/src/global.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/mcp-app-wrapper.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"name": "threejs-mcp",
|
||||
"version": "0.4.0",
|
||||
"description": "Three.js 3D visualization MCP App Server",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/modelcontextprotocol/ext-apps",
|
||||
"directory": "examples/threejs-server"
|
||||
},
|
||||
"files": [
|
||||
"server.ts",
|
||||
"server-utils.ts",
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "server.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --noEmit && cross-env INPUT=mcp-app.html vite build",
|
||||
"watch": "cross-env INPUT=mcp-app.html vite build --watch",
|
||||
"serve:http": "bun --watch server.ts",
|
||||
"serve:stdio": "bun server.ts --stdio",
|
||||
"start": "npm run start:http",
|
||||
"start:http": "cross-env NODE_ENV=development npm run build && npm run serve:http",
|
||||
"start:stdio": "cross-env NODE_ENV=development npm run build && npm run serve:stdio",
|
||||
"dev": "cross-env NODE_ENV=development concurrently 'npm run watch' 'npm run serve:http'",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/ext-apps": "^0.4.0",
|
||||
"@modelcontextprotocol/sdk": "^1.24.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"three": "^0.181.0",
|
||||
"zod": "^4.1.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cors": "^2.8.19",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^19.2.2",
|
||||
"@types/react-dom": "^19.2.2",
|
||||
"@types/three": "^0.181.0",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"concurrently": "^9.2.1",
|
||||
"cors": "^2.8.5",
|
||||
"cross-env": "^10.1.0",
|
||||
"express": "^5.1.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^6.0.0",
|
||||
"vite-plugin-singlefile": "^2.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
const config = {
|
||||
plugins: [],
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:751db54001e46ccf37d9cb26a4d59c079d076740c98a164436fe1d349e58600a
|
||||
size 5647
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Shared utilities for running MCP servers with Streamable HTTP transport.
|
||||
*/
|
||||
|
||||
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import cors from "cors";
|
||||
import type { Request, Response } from "express";
|
||||
|
||||
export interface ServerOptions {
|
||||
port: number;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts an MCP server with Streamable HTTP transport in stateless mode.
|
||||
*
|
||||
* @param createServer - Factory function that creates a new McpServer instance per request.
|
||||
* @param options - Server configuration options.
|
||||
*/
|
||||
export async function startServer(
|
||||
createServer: () => McpServer,
|
||||
options: ServerOptions,
|
||||
): Promise<void> {
|
||||
const { port, name = "MCP Server" } = options;
|
||||
|
||||
const app = createMcpExpressApp({ host: "0.0.0.0" });
|
||||
app.use(cors());
|
||||
|
||||
app.all("/mcp", async (req: Request, res: Response) => {
|
||||
const server = createServer();
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
});
|
||||
|
||||
res.on("close", () => {
|
||||
transport.close().catch(() => {});
|
||||
server.close().catch(() => {});
|
||||
});
|
||||
|
||||
try {
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
} catch (error) {
|
||||
console.error("MCP error:", error);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32603, message: "Internal server error" },
|
||||
id: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const httpServer = app.listen(port, (err) => {
|
||||
if (err) {
|
||||
console.error("Failed to start server:", err);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`${name} listening on http://localhost:${port}/mcp`);
|
||||
});
|
||||
|
||||
const shutdown = () => {
|
||||
console.log("\nShutting down...");
|
||||
httpServer.close(() => process.exit(0));
|
||||
};
|
||||
|
||||
process.on("SIGINT", shutdown);
|
||||
process.on("SIGTERM", shutdown);
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* Three.js MCP Server
|
||||
*
|
||||
* Provides tools for rendering interactive 3D scenes using Three.js.
|
||||
*/
|
||||
import {
|
||||
RESOURCE_MIME_TYPE,
|
||||
registerAppResource,
|
||||
registerAppTool,
|
||||
} from "@modelcontextprotocol/ext-apps/server";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import type { ReadResourceResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import { startServer } from "./server-utils.js";
|
||||
|
||||
// =============================================================================
|
||||
// Constants
|
||||
// =============================================================================
|
||||
|
||||
const DIST_DIR = path.join(import.meta.dirname, "dist");
|
||||
|
||||
// Default code example for the Three.js widget
|
||||
const DEFAULT_THREEJS_CODE = `const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
|
||||
renderer.setSize(width, height);
|
||||
renderer.setClearColor(0x1a1a2e);
|
||||
|
||||
const cube = new THREE.Mesh(
|
||||
new THREE.BoxGeometry(1, 1, 1),
|
||||
new THREE.MeshStandardMaterial({ color: 0x00ff88 })
|
||||
);
|
||||
scene.add(cube);
|
||||
|
||||
scene.add(new THREE.DirectionalLight(0xffffff, 1));
|
||||
scene.add(new THREE.AmbientLight(0x404040));
|
||||
|
||||
camera.position.z = 3;
|
||||
|
||||
function animate() {
|
||||
requestAnimationFrame(animate);
|
||||
cube.rotation.x += 0.01;
|
||||
cube.rotation.y += 0.01;
|
||||
renderer.render(scene, camera);
|
||||
}
|
||||
animate();`;
|
||||
|
||||
const THREEJS_DOCUMENTATION = `# Three.js Widget Documentation
|
||||
|
||||
## Available Globals
|
||||
- \`THREE\` - Three.js library (r181)
|
||||
- \`canvas\` - Pre-created canvas element
|
||||
- \`width\`, \`height\` - Canvas dimensions in pixels
|
||||
- \`OrbitControls\` - Interactive camera controls
|
||||
- \`EffectComposer\`, \`RenderPass\`, \`UnrealBloomPass\` - Post-processing effects
|
||||
|
||||
## Basic Template
|
||||
\`\`\`javascript
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
|
||||
renderer.setSize(width, height);
|
||||
renderer.setClearColor(0x1a1a2e); // Dark background
|
||||
|
||||
// Add objects here...
|
||||
|
||||
camera.position.z = 5;
|
||||
renderer.render(scene, camera); // Static render
|
||||
\`\`\`
|
||||
|
||||
## Example: Rotating Cube with Lighting
|
||||
\`\`\`javascript
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
|
||||
renderer.setSize(width, height);
|
||||
renderer.setClearColor(0x1a1a2e);
|
||||
|
||||
const cube = new THREE.Mesh(
|
||||
new THREE.BoxGeometry(1, 1, 1),
|
||||
new THREE.MeshStandardMaterial({ color: 0x00ff88 })
|
||||
);
|
||||
scene.add(cube);
|
||||
|
||||
// Lighting - keep intensity at 1 or below
|
||||
scene.add(new THREE.DirectionalLight(0xffffff, 1));
|
||||
scene.add(new THREE.AmbientLight(0x404040));
|
||||
|
||||
camera.position.z = 3;
|
||||
|
||||
function animate() {
|
||||
requestAnimationFrame(animate);
|
||||
cube.rotation.x += 0.01;
|
||||
cube.rotation.y += 0.01;
|
||||
renderer.render(scene, camera);
|
||||
}
|
||||
animate();
|
||||
\`\`\`
|
||||
|
||||
## Example: Interactive OrbitControls
|
||||
\`\`\`javascript
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
|
||||
renderer.setSize(width, height);
|
||||
renderer.setClearColor(0x2d2d44);
|
||||
|
||||
const controls = new OrbitControls(camera, renderer.domElement);
|
||||
controls.enableDamping = true;
|
||||
|
||||
const sphere = new THREE.Mesh(
|
||||
new THREE.SphereGeometry(1, 32, 32),
|
||||
new THREE.MeshStandardMaterial({ color: 0xff6b6b, roughness: 0.4 })
|
||||
);
|
||||
scene.add(sphere);
|
||||
|
||||
scene.add(new THREE.DirectionalLight(0xffffff, 1));
|
||||
scene.add(new THREE.AmbientLight(0x404040));
|
||||
|
||||
camera.position.z = 4;
|
||||
|
||||
function animate() {
|
||||
requestAnimationFrame(animate);
|
||||
controls.update();
|
||||
renderer.render(scene, camera);
|
||||
}
|
||||
animate();
|
||||
\`\`\`
|
||||
|
||||
## Tips
|
||||
- Always set \`renderer.setClearColor()\` to a dark color
|
||||
- Keep light intensity ≤ 1 to avoid washed-out scenes
|
||||
- Use \`MeshStandardMaterial\` for realistic lighting
|
||||
- For animations, use \`requestAnimationFrame\`
|
||||
`;
|
||||
|
||||
const resourceUri = "ui://threejs/mcp-app.html";
|
||||
|
||||
// =============================================================================
|
||||
// Server Setup
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Creates a new MCP server instance with tools and resources registered.
|
||||
* Each HTTP session needs its own server instance because McpServer only supports one transport.
|
||||
*/
|
||||
export function createServer(): McpServer {
|
||||
const server = new McpServer({
|
||||
name: "Three.js Server",
|
||||
version: "1.0.0",
|
||||
});
|
||||
|
||||
// Tool 1: show_threejs_scene
|
||||
registerAppTool(
|
||||
server,
|
||||
"show_threejs_scene",
|
||||
{
|
||||
title: "Show Three.js Scene",
|
||||
description:
|
||||
"Render an interactive 3D scene with custom Three.js code. Available globals: THREE, OrbitControls, EffectComposer, RenderPass, UnrealBloomPass, canvas, width, height.",
|
||||
inputSchema: {
|
||||
code: z
|
||||
.string()
|
||||
.default(DEFAULT_THREEJS_CODE)
|
||||
.describe("JavaScript code to render the 3D scene"),
|
||||
height: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.default(400)
|
||||
.describe("Height in pixels"),
|
||||
},
|
||||
outputSchema: z.object({
|
||||
code: z.string(),
|
||||
height: z.number(),
|
||||
}),
|
||||
_meta: { ui: { resourceUri } },
|
||||
},
|
||||
async ({ code, height }) => {
|
||||
const data = { code, height };
|
||||
return {
|
||||
content: [{ type: "text", text: JSON.stringify(data) }],
|
||||
structuredContent: data,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// Tool 2: learn_threejs (not a UI tool, just returns documentation)
|
||||
server.registerTool(
|
||||
"learn_threejs",
|
||||
{
|
||||
title: "Learn Three.js",
|
||||
description:
|
||||
"Get documentation and examples for using the Three.js widget",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
return {
|
||||
content: [{ type: "text", text: THREEJS_DOCUMENTATION }],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// Resource registration
|
||||
registerAppResource(
|
||||
server,
|
||||
resourceUri,
|
||||
resourceUri,
|
||||
{ mimeType: RESOURCE_MIME_TYPE, description: "Three.js Widget UI" },
|
||||
async (): Promise<ReadResourceResult> => {
|
||||
const html = await fs.readFile(
|
||||
path.join(DIST_DIR, "mcp-app.html"),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: resourceUri,
|
||||
mimeType: RESOURCE_MIME_TYPE,
|
||||
text: html,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (process.argv.includes("--stdio")) {
|
||||
await createServer().connect(new StdioServerTransport());
|
||||
} else {
|
||||
const port = parseInt(process.env.PORT ?? "3108", 10);
|
||||
await startServer(createServer, { port, name: "Three.js Server" });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
font-family:
|
||||
system-ui,
|
||||
-apple-system,
|
||||
sans-serif;
|
||||
font-size: 1rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: #1a1a2e;
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 400px;
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.error {
|
||||
padding: 20px;
|
||||
color: #ff6b6b;
|
||||
}
|
||||
|
||||
.threejs-container {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.error-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #ff6b6b;
|
||||
background: rgba(26, 26, 46, 0.9);
|
||||
border-radius: 8px;
|
||||
font-family: system-ui;
|
||||
padding: 20px;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Three.js Widget - MCP App Wrapper
|
||||
*
|
||||
* Generic wrapper that handles MCP App connection and passes all relevant
|
||||
* props to the actual widget component.
|
||||
*/
|
||||
import type { App, McpUiHostContext } from "@modelcontextprotocol/ext-apps";
|
||||
import { useApp } from "@modelcontextprotocol/ext-apps/react";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { StrictMode, useState, useCallback, useEffect } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import ThreeJSApp from "./threejs-app.tsx";
|
||||
import "./global.css";
|
||||
|
||||
// =============================================================================
|
||||
// Types
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Props passed to the widget component.
|
||||
* This interface can be reused for other widgets.
|
||||
*/
|
||||
export interface WidgetProps<TToolInput = Record<string, unknown>> {
|
||||
/** Complete tool input (after streaming finishes) */
|
||||
toolInputs: TToolInput | null;
|
||||
/** Partial tool input (during streaming) */
|
||||
toolInputsPartial: TToolInput | null;
|
||||
/** Tool execution result from the server */
|
||||
toolResult: CallToolResult | null;
|
||||
/** Host context (theme, dimensions, locale, etc.) */
|
||||
hostContext: McpUiHostContext | null;
|
||||
/** Call a tool on the MCP server */
|
||||
callServerTool: App["callServerTool"];
|
||||
/** Send a message to the host's chat */
|
||||
sendMessage: App["sendMessage"];
|
||||
/** Request the host to open a URL */
|
||||
openLink: App["openLink"];
|
||||
/** Send log messages to the host */
|
||||
sendLog: App["sendLog"];
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// MCP App Wrapper
|
||||
// =============================================================================
|
||||
|
||||
function McpAppWrapper() {
|
||||
const [toolInputs, setToolInputs] = useState<Record<string, unknown> | null>(
|
||||
null,
|
||||
);
|
||||
const [toolInputsPartial, setToolInputsPartial] = useState<Record<
|
||||
string,
|
||||
unknown
|
||||
> | null>(null);
|
||||
const [toolResult, setToolResult] = useState<CallToolResult | null>(null);
|
||||
const [hostContext, setHostContext] = useState<McpUiHostContext | null>(null);
|
||||
|
||||
const { app, error } = useApp({
|
||||
appInfo: { name: "Three.js Widget", version: "1.0.0" },
|
||||
capabilities: {},
|
||||
onAppCreated: (app) => {
|
||||
// Complete tool input (streaming finished)
|
||||
app.ontoolinput = (params) => {
|
||||
setToolInputs(params.arguments as Record<string, unknown>);
|
||||
setToolInputsPartial(null);
|
||||
};
|
||||
// Partial tool input (streaming in progress)
|
||||
app.ontoolinputpartial = (params) => {
|
||||
setToolInputsPartial(params.arguments as Record<string, unknown>);
|
||||
};
|
||||
// Tool execution result
|
||||
app.ontoolresult = (params) => {
|
||||
setToolResult(params as CallToolResult);
|
||||
};
|
||||
// Host context changes (theme, dimensions, etc.)
|
||||
app.onhostcontextchanged = (params) => {
|
||||
setHostContext((prev) => ({ ...prev, ...params }));
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// Get initial host context after connection
|
||||
useEffect(() => {
|
||||
if (app) {
|
||||
const ctx = app.getHostContext();
|
||||
if (ctx) {
|
||||
setHostContext(ctx);
|
||||
}
|
||||
}
|
||||
}, [app]);
|
||||
|
||||
// Memoized callbacks that forward to app methods
|
||||
const callServerTool = useCallback<App["callServerTool"]>(
|
||||
(params, options) => app!.callServerTool(params, options),
|
||||
[app],
|
||||
);
|
||||
const sendMessage = useCallback<App["sendMessage"]>(
|
||||
(params, options) => app!.sendMessage(params, options),
|
||||
[app],
|
||||
);
|
||||
const openLink = useCallback<App["openLink"]>(
|
||||
(params, options) => app!.openLink(params, options),
|
||||
[app],
|
||||
);
|
||||
const sendLog = useCallback<App["sendLog"]>(
|
||||
(params) => app!.sendLog(params),
|
||||
[app],
|
||||
);
|
||||
|
||||
if (error) {
|
||||
return <div className="error">Error: {error.message}</div>;
|
||||
}
|
||||
|
||||
if (!app) {
|
||||
return <div className="loading">Connecting...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ThreeJSApp
|
||||
toolInputs={toolInputs}
|
||||
toolInputsPartial={toolInputsPartial}
|
||||
toolResult={toolResult}
|
||||
hostContext={hostContext}
|
||||
callServerTool={callServerTool}
|
||||
sendMessage={sendMessage}
|
||||
openLink={openLink}
|
||||
sendLog={sendLog}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<McpAppWrapper />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,232 @@
|
||||
/**
|
||||
* Three.js App Component
|
||||
*
|
||||
* Renders interactive 3D scenes using Three.js with streaming code preview.
|
||||
* Receives all MCP App props from the wrapper.
|
||||
*/
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
|
||||
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
|
||||
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
|
||||
import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass.js";
|
||||
import type { WidgetProps } from "./mcp-app-wrapper.tsx";
|
||||
|
||||
// =============================================================================
|
||||
// Types
|
||||
// =============================================================================
|
||||
|
||||
interface ThreeJSToolInput {
|
||||
code?: string;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
type ThreeJSAppProps = WidgetProps<ThreeJSToolInput>;
|
||||
|
||||
// =============================================================================
|
||||
// Constants
|
||||
// =============================================================================
|
||||
|
||||
// Default demo code shown when no code is provided
|
||||
const DEFAULT_THREEJS_CODE = `const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
|
||||
renderer.setSize(width, height);
|
||||
renderer.setClearColor(0x1a1a2e);
|
||||
|
||||
const cube = new THREE.Mesh(
|
||||
new THREE.BoxGeometry(1, 1, 1),
|
||||
new THREE.MeshStandardMaterial({ color: 0x00ff88 })
|
||||
);
|
||||
// Start with an isometric-ish rotation to show 3 faces
|
||||
cube.rotation.x = 0.5;
|
||||
cube.rotation.y = 0.7;
|
||||
scene.add(cube);
|
||||
|
||||
// Better lighting: key light + fill light + ambient
|
||||
const keyLight = new THREE.DirectionalLight(0xffffff, 1.2);
|
||||
keyLight.position.set(1, 1, 2);
|
||||
scene.add(keyLight);
|
||||
const fillLight = new THREE.DirectionalLight(0x8888ff, 0.4);
|
||||
fillLight.position.set(-1, 0, -1);
|
||||
scene.add(fillLight);
|
||||
scene.add(new THREE.AmbientLight(0x404040, 0.5));
|
||||
|
||||
camera.position.z = 3;
|
||||
|
||||
function animate() {
|
||||
requestAnimationFrame(animate);
|
||||
cube.rotation.x += 0.01;
|
||||
cube.rotation.y += 0.01;
|
||||
renderer.render(scene, camera);
|
||||
}
|
||||
animate();`;
|
||||
|
||||
// =============================================================================
|
||||
// Streaming Preview
|
||||
// =============================================================================
|
||||
|
||||
const SHIMMER_STYLE = `
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
`;
|
||||
|
||||
function LoadingShimmer({ height, code }: { height: number; code?: string }) {
|
||||
const preRef = useRef<HTMLPreElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (preRef.current) preRef.current.scrollTop = preRef.current.scrollHeight;
|
||||
}, [code]);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: "100%",
|
||||
height,
|
||||
borderRadius: 8,
|
||||
padding: 16,
|
||||
boxSizing: "border-box",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
background:
|
||||
"linear-gradient(90deg, #1a1a2e 25%, #2d2d44 50%, #1a1a2e 75%)",
|
||||
backgroundSize: "200% 100%",
|
||||
animation: "shimmer 1.5s ease-in-out infinite",
|
||||
}}
|
||||
>
|
||||
<style>{SHIMMER_STYLE}</style>
|
||||
<div
|
||||
style={{
|
||||
color: "#888",
|
||||
fontFamily: "system-ui",
|
||||
fontSize: 12,
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
🎮 Three.js
|
||||
</div>
|
||||
{code && (
|
||||
<pre
|
||||
ref={preRef}
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
flex: 1,
|
||||
overflow: "auto",
|
||||
color: "#aaa",
|
||||
fontFamily: "monospace",
|
||||
fontSize: 11,
|
||||
lineHeight: 1.4,
|
||||
whiteSpace: "pre-wrap",
|
||||
wordBreak: "break-word",
|
||||
}}
|
||||
>
|
||||
{code}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Three.js Execution
|
||||
// =============================================================================
|
||||
|
||||
const threeContext = {
|
||||
THREE,
|
||||
OrbitControls,
|
||||
EffectComposer,
|
||||
RenderPass,
|
||||
UnrealBloomPass,
|
||||
};
|
||||
|
||||
async function executeThreeCode(
|
||||
code: string,
|
||||
canvas: HTMLCanvasElement,
|
||||
width: number,
|
||||
height: number,
|
||||
): Promise<void> {
|
||||
const fn = new Function(
|
||||
"ctx",
|
||||
"canvas",
|
||||
"width",
|
||||
"height",
|
||||
`const { THREE, OrbitControls, EffectComposer, RenderPass, UnrealBloomPass } = ctx;
|
||||
return (async () => { ${code} })();`,
|
||||
);
|
||||
await fn(threeContext, canvas, width, height);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Main Component
|
||||
// =============================================================================
|
||||
|
||||
export default function ThreeJSApp({
|
||||
toolInputs,
|
||||
toolInputsPartial,
|
||||
toolResult: _toolResult,
|
||||
hostContext,
|
||||
callServerTool: _callServerTool,
|
||||
sendMessage: _sendMessage,
|
||||
openLink: _openLink,
|
||||
sendLog: _sendLog,
|
||||
}: ThreeJSAppProps) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const height = toolInputs?.height ?? toolInputsPartial?.height ?? 400;
|
||||
const code = toolInputs?.code || DEFAULT_THREEJS_CODE;
|
||||
const partialCode = toolInputsPartial?.code;
|
||||
const isStreaming = !toolInputs && !!toolInputsPartial;
|
||||
|
||||
const safeAreaInsets = hostContext?.safeAreaInsets;
|
||||
const containerStyle = {
|
||||
paddingTop: safeAreaInsets?.top,
|
||||
paddingRight: safeAreaInsets?.right,
|
||||
paddingBottom: safeAreaInsets?.bottom,
|
||||
paddingLeft: safeAreaInsets?.left,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!code || !canvasRef.current || !containerRef.current) return;
|
||||
|
||||
setError(null);
|
||||
const width = containerRef.current.offsetWidth || 800;
|
||||
executeThreeCode(code, canvasRef.current, width, height).catch((e) =>
|
||||
setError(e instanceof Error ? e.message : "Unknown error"),
|
||||
);
|
||||
}, [code, height]);
|
||||
|
||||
if (isStreaming || !code) {
|
||||
return (
|
||||
<div style={containerStyle}>
|
||||
<LoadingShimmer height={height} code={partialCode} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="threejs-container"
|
||||
style={containerStyle}
|
||||
>
|
||||
<canvas
|
||||
id="threejs-canvas"
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
width: "100%",
|
||||
height,
|
||||
borderRadius: 8,
|
||||
display: "block",
|
||||
background: "#1a1a2e",
|
||||
}}
|
||||
/>
|
||||
{error && <div className="error-overlay">Error: {error}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"code": "const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(60, width/height, 0.1, 100); camera.position.set(2, 2, 2); camera.lookAt(0, 0.5, 0); const renderer = new THREE.WebGLRenderer({canvas, antialias: true}); renderer.setSize(width, height); renderer.shadowMap.enabled = true; const cube = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial({color: 0xff4444})); cube.castShadow = true; cube.position.y = 0.5; scene.add(cube); const floor = new THREE.Mesh(new THREE.PlaneGeometry(5,5), new THREE.MeshStandardMaterial({color: 0x222233})); floor.rotation.x = -Math.PI/2; floor.receiveShadow = true; scene.add(floor); const light = new THREE.DirectionalLight(0xffffff, 2); light.position.set(3, 5, 3); light.castShadow = true; scene.add(light); scene.add(new THREE.AmbientLight(0x404040)); function animate() { requestAnimationFrame(animate); cube.rotation.y += 0.01; renderer.render(scene, camera); } animate();"
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src", "server.ts"]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { viteSingleFile } from "vite-plugin-singlefile";
|
||||
|
||||
const INPUT = process.env.INPUT;
|
||||
if (!INPUT) {
|
||||
throw new Error("INPUT environment variable is not set");
|
||||
}
|
||||
|
||||
const isDevelopment = process.env.NODE_ENV === "development";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), viteSingleFile()],
|
||||
build: {
|
||||
sourcemap: isDevelopment ? "inline" : undefined,
|
||||
cssMinify: !isDevelopment,
|
||||
minify: !isDevelopment,
|
||||
|
||||
rollupOptions: {
|
||||
input: INPUT,
|
||||
},
|
||||
outDir: "dist",
|
||||
emptyOutDir: false,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": ["node_modules", "threejs-server"]
|
||||
}
|
||||
Reference in New Issue
Block a user