하나의 TypeScript 파일을 AI 클라이언트와 사용자가 호출할 수 있는 CLI 도구, MCP server, 웹 인터페이스로 변환합니다.
다른 이름 portel-dev/photon, @portel/photon
- 스타
- 100
- Tools
- —
- 다운로드, 30일
- —
- 최신 버전
- —
- 마지막 커밋
- 2026년 10월 19일
- 라이선스
- MIT
Photon MCP란?
하나의 TypeScript 파일을 AI 클라이언트와 사용자가 호출할 수 있는 CLI 도구, MCP server, 웹 인터페이스로 변환합니다.
프로젝트 README에서 생성된 요약
Photon MCP server 정보
개발자는 단 하나의 TypeScript 파일로 CLI 도구, MCP server, 웹 인터페이스를 포함한 완전한 인터페이스 세트를 구축할 수 있습니다. 특정 메서드 시그니처와 JSDoc 주석이 포함된 TypeScript 클래스를 작성하면, 사람 사용자와 AI 에이전트 모두를 위한 필요한 계약(contract)이 자동으로 생성됩니다. 이를 통해 하나의 로직을 커맨드라인 유틸리티, Beam이라 불리는 웹 대시보드, 그리고 Claude, ChatGPT, Cursor와 같은 AI 클라이언트를 위한 도구로 활용할 수 있습니다.
로컬 MCP server 설정은 명령줄에서 photon mcp install을 통해 수행합니다. 이 시스템은 Claude Desktop을 위한 로컬 stdio 연결과 ChatGPT 개발자 모드를 위한 공개 HTTPS 엔드포인트를 지원합니다. Node.js 20 이상이 필요하며, 별도의 설정 파일 없이 내부적으로 모든 TypeScript 컴파일을 처리합니다. 이러한 방식은 에이전트가 도구를 호출하든 사람이 자동 생성된 웹 폼을 사용하든, 모든 인터페이스에서 동일한 검증 규칙, 문서 및 타입이 일관되게 적용되도록 보장합니다.
활용 사례
- 1MCP server 배포TypeScript 기능을 Claude Desktop 또는 기타 MCP 호환 클라이언트 내의 도구로 등록합니다.
- 2사용자 친화적 인터페이스 생성프론트엔드 코드를 작성하지 않고도 수동 도구 테스트 및 데이터 입력을 위한 대화형 웹 대시보드를 만듭니다.
- 3CLI를 통한 작업 자동화스크립트 및 자동화를 위해 터미널에서 특정 TypeScript 메서드를 직접 실행합니다.
- 4프로덕션 워크플로우 구축단순한 메서드를 웹훅, 스케줄, 감사 기록을 갖춘 복잡한 시스템으로 확장합니다.
프로젝트의 README를 바탕으로 작성되었습니다. 모든 활용 사례는 해당 내용의 인용문과 대조하여 확인합니다.
Photon MCP 설치 방법
형식 확인: 2026년 11월 10일Cursor에 추가Goose에 추가Claude Code에 Photon MCP 설치
$ claude mcp add photon -- npx -y @portel/photonCursor에 Photon MCP 설치
~/.cursor/mcp.json
{
"mcpServers": {
"photon": {
"command": "npx",
"args": [
"-y",
"@portel/photon"
]
}
}
}VS Code에 Photon MCP 설치
.vscode/mcp.json
{
"servers": {
"photon": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@portel/photon"
]
}
}
}VS Code CLI에 Photon MCP 설치
$ code --add-mcp '{"name":"photon","type":"stdio","command":"npx","args":["-y","@portel/photon"]}'Claude Desktop에 Photon MCP 설치
claude_desktop_config.json
{
"mcpServers": {
"photon": {
"command": "npx",
"args": [
"-y",
"@portel/photon"
]
}
}
}Codex에 Photon MCP 설치
$ codex mcp add photon -- npx -y @portel/photonCodex config.toml에 Photon MCP 설치
~/.codex/config.toml
[mcp_servers.photon] command = "npx" args = ["-y", "@portel/photon"]
Gemini CLI에 Photon MCP 설치
$ gemini mcp add -s user photon npx -- -y @portel/photonGemini settings.json에 Photon MCP 설치
~/.gemini/settings.json
{
"mcpServers": {
"photon": {
"command": "npx",
"args": [
"-y",
"@portel/photon"
]
}
}
}자동 검사
2026년 11월 12일에 실행됨전체 보고서 →자동 검사를 통과했습니다. 이는 보안 감사가 아닙니다. 코드를 직접 읽고 서버에 필요한 최소한의 권한만 부여하십시오. 검사 방식
- 소스 저장소 연결 및 접근 가능통과
- 오픈 소스 라이선스 (OSI)통과
- 최근 1년 내 커밋 또는 릴리스통과
- 패키지 이름이 인기 패키지와 유사하지 않음통과
- 원격 엔드포인트가 HTTPS 사용검사되지 않음
- 파괴적인 도구에 라벨 표시됨검사되지 않음
- 모델에 대한 숨겨진 지침 없음통과
- 패키지 및 해당 종속성에 중요한 보안 권고 없음검사되지 않음
README
GitHub에서 보기One TypeScript capability becomes the whole agent stack.
Photon is the fastest way to turn a small, verified TypeScript method into something humans can operate and agents can trust. Write the capability once; Photon derives the interfaces, contracts, and runtime behavior around it:
- MCP server for Claude, ChatGPT, Cursor, and agents
- Embedded app UI for chat clients that support MCP app resources
- CLI tool for scripts, demos, and automation
- Beam web interface for humans
- Web routes, schedules, webhooks, retries, state, and audit history when the capability grows into a production workflow
Photon is free and open source software released under the MIT license. Full documentation lives at photon.portel.dev.
Related Portel project: NCP gives agents one natural MCP interface to discover and run tools across a whole tool ecosystem. Photon builds reliable agent-facing capabilities; NCP helps agents find and use them alongside every other MCP.
Try it in two minutes:
bun add -g @portel/photon
photon new my-tool
photon
That opens Beam, the generated human UI. Add photon mcp install my-tool when
you want the same capability inside Claude Desktop or another MCP client.
Interfaces are optional. Intent is mandatory.
gh repo star portel-dev/photon
From one method to every surface
The weather example is intentionally small: one TypeScript method, a few
docblock tags, and one @ui HTML asset. Photon turns that into a CLI command,
Beam UI, MCP tool, and embedded app surface for MCP app-capable chat clients.
Claude Desktop can run it from a local stdio MCP command; ChatGPT developer
mode can connect to the same Photon over a public HTTPS /mcp endpoint.
Real clients, same Photon:
Follow the step-by-step tutorial
or open the runnable example in
examples/weather-showcase.
The tutorial also includes Beam, CLI, and a concept animation for the full
transformation.
The Photon Promise
Photon is the modern dev stack for the agentic age: each photon is a small, auditable brick that can be used by humans, agents, schedulers, webhooks, and apps without rewriting the same capability for every interface.
That is the core idea: tiny trusted capabilities compose into larger systems. A photon can start as a helper method, become a CLI command, render as an app, run on a schedule, accept webhooks, and still expose a clean agent-readable contract.
Example
// hello.photon.ts
export default class Hello {
greet(name: string) {
return `Hello, ${name}!`;
}
}
That's a complete photon. From this single file you get:
$ photon cli hello greet --name Ada # CLI
$ photon # Web UI at localhost:3008
$ photon mcp hello # MCP server for Claude, Cursor, etc.
No decorators. No registration. No server boilerplate. Just define the intent. Photon handles the rest.
Quick Start
From zero to an MCP server connected to Claude Desktop in three commands:
bun add -g @portel/photon
photon new my-tool # Scaffolds ./my-tool.photon.ts in your CWD
photon mcp install my-tool # Registers it in Claude Desktop's config
# Restart Claude Desktop. Your tool is live.
Prefer the web dashboard? Skip step 3 and run photon instead — it opens Beam, the auto-generated UI.
Or try without installing globally:
bunx @portel/photon new my-tool
bunx @portel/photon mcp install my-tool
# pnpm users can use pnpm dlx instead:
pnpm dlx @portel/photon new my-tool
pnpm dlx @portel/photon mcp install my-tool
Requires Node.js 20+. TypeScript is compiled internally; no
tsconfig.jsonneeded.Where do photon files live?
./(a project directory you cd into) or~/.photon/(global, auto-discovered). User settings persist under~/.photon/state/<photon>/. See Where things live.
How It Works
You write a TypeScript class. Methods are your capabilities. Types describe what's valid. Comments explain the intent. Photon reads all of it and generates three interfaces from one file. Same logic. Same validation. Same data.
analytics.photon.ts → Beam · Web app · Webhook · WebSocket · CLI · MCP
The more you express, the more Photon derives:
| What you write | What Photon derives |
|---|---|
| Method signatures | Tool definitions: names, inputs, outputs |
| Type annotations | Input validation rules, UI field types |
| JSDoc comments | Documentation for AI clients and human users |
| Constructor parameters | Config UI, environment variable mapping, runtime injection (Photon, Cloudflare, CloudflareEnv) |
@tags |
Validation, formatting, scheduling, webhooks, and HTTP routes |
When you add a @param city {@pattern ^[a-zA-Z\s]+$} annotation, Beam validates it in the form, the CLI validates it before running, and the MCP schema enforces it for the AI. One annotation. Three consumers.
Three ways to author
extends Photon is one shape. You can also inject Photon as a constructor parameter when you already extend something else, or compose without inheritance — same API either way. CF resources reach the photon through a separate Cloudflare injection so portable photons stay portable. See docs/guides/PHOTON-INJECTION.md.
Reuse a Photon in application code
Existing Photons can also be application dependencies. Load their source through the public API and call methods from your own Node code:
import { createPhotonRuntime } from '@portel/photon';
const runtime = createPhotonRuntime();
try {
const todo = await runtime.photon<{
add(text: string): Promise<unknown>;
}>('./todo.photon.ts', { baseDir: '/srv/my-app/photons' });
await todo.add('Review the release');
} finally {
await runtime.close();
}
This manages initialization and shutdown without starting a server. It executes trusted code in your application process; the host owns authorization. The object is separate from a live Beam/daemon instance. Use MCP when your application needs to operate on that same live instance. For source resolution, persistence, and constructor-dependency lifecycle limits, see Photon as a library.
Beam: Human Exploration
Run the shared task-board walkthrough to see a human and an MCP client operate the same state.
Beam is the web dashboard. Every photon becomes an interactive form automatically. Run photon. That's the whole command.
The UI is fully auto-generated from your method signatures: field types, validation, defaults, layouts. You never write frontend code. When you add a {@choice a,b,c} tag to a parameter, Beam renders a dropdown. When you mark a string as {@format email}, the field validates email format. The UI evolves as your code does.
When forms aren't the right interface for what you're building, you can replace Beam's auto-generated view with your own HTML. A global named after your photon is auto-injected (e.g., analytics.onResult(data => ...)) — no framework required. window.photon.url is also injected and resolves to the Beam base URL so your HTML can construct fetch paths correctly whether running locally or behind a reverse proxy.
Custom UIs follow the official MCP Apps Extension and work across compatible hosts. See the Custom UI Guide.
Photons that declare HTTP routes with @get, @post, @put, @patch, or @delete are shown in Beam as web apps. Routes support dynamic path segments (e.g. @get /items/:id) matched by specificity: literal segments win over parameters. Beam proxies requests to those routes and injects an x-photon-base-path header so the app can construct correct absolute paths regardless of where Beam is hosted. Web apps and WebSockets are Photon application targets; MCP Apps are a separate official MCP extension for embedded UI resources.
AI Agents: Machine Invocation
Photon ships separate, tested MCP adapters: sessionful MCP 2025 over stdio and
Streamable HTTP, plus stateless MCP 2026-07-28 release-candidate support over
Streamable HTTP. See the
compatibility matrix and runnable clients,
or run photon doctor mcp against your installed runtime.
photon info analytics --mcp
{
"mcpServers": {
"analytics": {
"command": "photon",
"args": ["mcp", "analytics"]
}
}
}
Paste into your AI client's config. Your photon is now an MCP server. Claude can call your methods. Cursor can call your methods. Any MCP-compatible host can call your methods.
The AI sees the same thing a human sees in Beam: the method names, the parameter descriptions from your JSDoc, the validation rules from your types. The JSDoc comment you wrote to document the tool for yourself is what Claude reads to decide when and how to call it.
The MCP tools themselves work with Claude Desktop, Claude Code, Cursor, and any MCP-compatible client. When your photon has a custom UI, clients that support the MCP Apps Extension can render it natively, as shown in the weather proof above.
How a Photon Evolves
Here is how a photon grows. Each step adds one thing and gets multiple capabilities from it.
Add comments: AI understands your intent
/**
* Weather - Check weather forecasts worldwide
*/
export default class Weather {
/**
* Get the weather forecast for a city
* @param city City name (e.g., "London")
*/
async forecast(params: { city: string }) { ... }
}
The class description becomes how AI clients introduce the tool to users. The @param description is what the AI reads before deciding what value to pass. Same comments. Human help text and AI contract at once.
Declare configuration: a settings tool appears
export default class Weather {
/** User-tunable knobs. Photon auto-generates a `settings` tool from this. */
protected settings = {
/** Units for forecast values */
units: 'metric',
/** Polling interval in seconds */
pollIntervalSec: 300,
};
async forecast(params: { city: string }) {
const res = await fetch(`...?units=${this.settings.units}`);
return await res.json();
}
}
protected settings is the canonical way to expose runtime knobs. Photon reads the JSDoc on each property, generates an MCP settings tool with typed inputs, and persists user changes to ~/.photon/state/<photon>/<instance>-settings.json. Inside methods, this.settings is a read-only Proxy. To change a value, the user (or AI) calls the auto-generated settings tool.
For secrets that should never be persisted in a settings file (API keys, tokens), use a constructor parameter instead. Photon maps the parameter name to an env var:
export default class Weather {
constructor(private apiKey: string) {} // → WEATHER_API_KEY
}
The constructor pattern is for primitives that come from .env. The protected settings pattern is for everything else, including any knob the user should be able to change at runtime without restarting. When in doubt, reach for settings.
Add tags: behavior extends across all surfaces
/**
* @dependencies node-fetch@^3.0.0
*/
export default class Weather {
/**
* @param city City name {@example London} {@pattern ^[a-zA-Z\s]+$}
* @param days Number of days {@min 1} {@max 7}
* @format table
*/
async forecast(params: { city: string; days?: number }) { ... }
}
@dependencies installs node-fetch automatically on first run, no manual package install needed. The {@pattern} validates in the form, the CLI, and the MCP schema simultaneously. days becomes a number spinner with bounds. @format table renders the result as a table in Beam. One annotation, three surfaces.
System CLI dependencies
If your photon wraps a command-line tool, declare it and Photon enforces it at load time:
/**
* @cli ffmpeg - https://ffmpeg.org/download.html
*/
export default class VideoProcessor {
async convert({ input, format }: { input: string; format: string }) {
// ffmpeg is guaranteed to exist when this runs
}
}
What Comes for Free
Things you don't build because Photon handles them:
| Auto-UI | Forms, field types, validation, layouts generated from your signatures |
| Stateful instances | Multiple named instances of the same photon, each with isolated state |
| Persistent memory | this.memory gives your photon per-instance key-value storage, no database needed |
| Scheduled execution | @scheduled runs any method on a cron schedule |
| Webhooks | @webhook exposes any method as an HTTP endpoint |
| OAuth (client) | Built-in OAuth 2.0 flows for Google, GitHub, Microsoft |
| OAuth Authorization Server | Issue tokens to MCP clients yourself: CIMD + DCR, PKCE, OIDC id_token, RFC 8693 token exchange |
| SQLite persistence | Audit log, execution history, and OAuth grants survive daemon restart (bun:sqlite or better-sqlite3) |
| Daemon ops | photon ps lists and controls scheduled jobs, webhooks, and live sessions |
| Distributed locks | @locked serializes access: one caller at a time, across processes |
| Cross-photon calls | this.call() invokes another photon's methods |
| Cloudflare runtime | this.cf.r2('blobs'), this.cf.d1('app'), this.cf.kv('cache') — same shape locally (miniflare) and deployed (real bindings). See CF-BINDINGS.md |
| Real-time events | this.emit() fires named events to the browser UI with zero wiring |
| Live rendering | this.render() pushes formatted output to CLI and Beam in real time |
| Delegated LLM | this.sample() asks the driving agent's model to generate text — no API key, agent pays |
| Inline confirm / input | this.confirm() and this.elicit() route through the client's native UI (Beam dialog, Claude prompt) |
| Scoped remote access | photon claim generates a short-lived code to scope a remote MCP session to one directory |
| Standalone binaries | photon build compiles any photon to a single executable via Bun |
| Dependency management | @dependencies auto-installs npm packages on first run |
Coordination: Locks + Events
Two primitives. Together they unlock a class of things that are surprisingly hard to build today.
Locks serialize access. When a method is marked @locked, only one caller can execute at a time, whether that caller is a human in Beam, a CLI script, or an AI agent. Everyone else waits their turn.
Events push state changes to any browser UI in real time. this.emit({ event: 'boardUpdated', data: board }) on the server becomes chess.onBoardUpdated(handler) in your custom UI — named after your photon file. No WebSockets to configure. No polling. Events are delivered via SSE through the MCP Streamable HTTP transport.
Together: turn-based coordination with live state.
export default class Chess {
/** Make a move. Locks ensure human and AI alternate turns. */
/** @locked */
async move(params: { from: string; to: string }) {
const result = await this.applyMove(params.from, params.to);
// Browser UI updates instantly, no polling needed
this.emit({ event: 'boardUpdated', data: result.board });
this.emit({ event: 'turnChanged', data: { next: result.nextPlayer } });
return result;
}
}
// In your custom UI (ui/chess.html)
// The global `chess` is auto-injected, named after your photon file
chess.onBoardUpdated(board => renderBoard(board));
chess.onTurnChanged(({ next }) => showTurn(next));
// Call server methods directly
chess.move({ from: 'e2', to: 'e4' });
A human moves through Beam. Claude is configured with the MCP server. The lock ensures they truly alternate. Events keep the board live on both sides. That's a fully functional turn-based chess game, human vs AI, in about 50 lines of application logic.
The same pattern applies beyond games: approval workflows where a human reviews before AI continues, collaborative tools where edits from any source appear instantly, simulations where steps must execute in strict sequence, any system where who acts next matters.
MCP Primitives on this
The MCP protocol's user-facing primitives are surfaced as plain methods on every photon instance — no decorators, no capability flags, no SDK imports. The runtime routes each call through whichever surface the request arrived on (Beam, Claude Desktop, Cursor, CLI).
export default class Editor {
async summarize(params: { text: string }) {
// Ask the driving agent's LLM. No API key. Agent pays.
return await this.sample({
prompt: `Summarize in one sentence:\n\n${params.text}`,
maxTokens: 128,
});
}
async deploy() {
if (!(await this.confirm('Ship to production?'))) return;
const env = await this.elicit<string>({
ask: 'select',
message: 'Which environment?',
options: ['staging', 'prod'],
});
await this.run(env);
}
}
| Primitive | What it does |
|---|---|
await this.sample({ prompt }) |
Delegates LLM generation to the caller's model via MCP sampling |
await this.confirm(question) |
Yes/no prompt — returns boolean |
await this.elicit(params) |
Arbitrary input (text, select, form, file, etc.) |
this.status(msg) / this.progress(v) |
Live feedback during long work; routes to SSE stream in Beam |
this.roots |
MCP workspace roots declared by the connected client (roots/list) |
this.notifyResourceUpdated(uri) |
Push notifications/resources/updated to subscribed clients |
Full reference: docs/reference/MCP-PRIMITIVES.md.
Remote Access: Claim Codes
By default every installed photon is visible to every connected MCP client. When you want to pair a remote agent with a subset of your photons — your phone driving Beam, a teammate reviewing one project, a CI agent scoped to a single directory — generate a claim code:
$ photon claim --scope /workspace/proj --ttl 4h --label "phone"
✓ Claim code: R3K-9QZ
Scope: /workspace/proj
Expires in: 4h
The remote client presents the code as the Mcp-Claim-Code header on
its MCP session. tools/list then only exposes photons whose source
lives under that directory. Sessions without a code keep full access —
the feature is strictly opt-in.
Full reference: docs/reference/CLAIM-CODES.md.
Marketplace
A curated set of photons is ready to install. The public gallery is now kept small on purpose: polished apps and tools in one place, teaching examples in another.
photon search boards
photon add boards
You can also install directly from any GitHub repository using qualified refs:
photon add owner/repo/photon-name
Browse the Photon Apps marketplace for ready-to-use photons, or the Photon Examples marketplace for focused learning examples. You can also host a private marketplace for your team: internal tools that stay off the public internet.
Commands
# Run
photon # Open Beam UI
photon mcp <name> # Run as MCP server
photon mcp <name> --dev # MCP server with hot reload
photon cli <name> [method] # Run as CLI tool
# Install from GitHub
photon beam owner/repo/name # Install & open in Beam
photon cli owner/repo/name method # Install & run via CLI
# Create
photon maker new <name> # Scaffold a new photon
# Build
photon build <name> # Compile to standalone binary
photon build <name> --with-app # Include Beam UI in binary
Photon MCP 질문
Photon MCP를 Claude Code에 추가하려면 어떻게 하나요?
터미널에서 claude mcp add photon -- npx -y @portel/photon를 실행합니다. 모든 프로젝트에서 사용할 수 있게 하려면 --scope user를 추가합니다.
Photon MCP를 Cursor에 추가하려면 어떻게 하나요?
~/.cursor/mcp.json를 열고 mcpServers 아래에 서버를 추가합니다. 위 설치 섹션에 표시된 Cursor 구성을 사용합니다.
Claude Desktop에서 Photon 도구를 MCP server로 설치하려면 어떻게 하나요?
photon mcp install <name>을 실행하여 Claude Desktop 설정에 등록한 후, Claude Desktop을 재시작하십시오. 또는 photon info <name> --mcp를 사용하여 AI 클라이언트에 붙여넣을 수 있는 JSON 설정 스니펫을 출력할 수 있습니다.
Photon은 하나의 TypeScript 파일로부터 어떤 인터페이스를 생성할 수 있나요?
Photon은 MCP server, 임베디드 앱 UI, CLI 도구, Beam 웹 인터페이스를 비롯하여 웹 라우트, 스케줄, 웹훅, 상태 및 감사 기록을 생성합니다.
Photon을 사용하려면 데코레이터나 서버 보일러플레이트가 필요한가요?
아니요. 메서드가 포함된 일반적인 export TypeScript 클래스만 있으면 충분합니다. Photon이 이를 바탕으로 CLI, 웹 UI, MCP server를 생성합니다.
Photon 실행을 위해 어떤 런타임이 필요한가요?
Photon은 Node.js 20 이상이 필요하며 내부적으로 TypeScript를 컴파일하므로 별도의 tsconfig.json이 필요하지 않습니다.
Photon은 여러 인터페이스 간에 매개변수를 어떻게 검증하나요?
@pattern과 같은 단일 파라미터 태그를 사용하면 Beam 폼, CLI, MCP 스키마 모두에 동시에 적용됩니다.