Files in the top-level directory from the latest check-in
- .fossil-settings
- .grok
- docs
- examples
- p2_mcp
- templates
- tests
- bootstrap.sh
- LICENSE
- pyproject.toml
- README.md
P2-cookbook • P2 Spin2 MCP Server
Production-ready Model Context Protocol (MCP) server for the Parallax Propeller 2 (P2) microcontroller and Spin2/PASM2 languages.
Enables AI agents (Grok, Claude, Cursor, etc.) to maximally exploit the P2's unique architecture:
- 8 independent, deterministic cogs with minimal context-switch cost
- 512 KB shared Hub RAM + 512 longs private Cog RAM + 512 longs LUT per cog
- Hardware XBYTE bytecode execution engine (6-clock dispatch, custom VMs)
- Pipelined 32-bit CORDIC solver (trig, vector, log, hyperbolic — shared hub resource)
- 64 Smart Pins with 34+ autonomous modes (PWM, UART, ADC, USB, etc.)
- Streamer (DMA/video), colorspace converter, pixel mixer, FIFO
- Cooperative multitasking + prioritized interrupts (3 per cog) + events/locks/COGATN
- True parallel execution with hybrid shared/private memory models
This MCP turns agents into expert P2 hardware architects, low-level optimizers, and multi-cog system designers.
All version control is Fossil SCM only (see fossil-scm-mcp). Never git.
Features (as powerful as possible)
Spin2 & PASM2 Mastery
- Intelligent generation, completion, refactoring, cycle-accurate optimization of Spin2 + inline/standalone PASM2.
- Emphasis on: conditional execution, instruction skipping (SKIPF/SKIPT), hub access scheduling (hub windows), tight loops, hybrid Spin2/PASM2 for best perf, self-modifying code where safe.
- Performance suggestions with cycle counts, hub contention analysis, overclock considerations.
XBYTE Advanced Exploitation
- Tools to design, generate, and optimize custom bytecode interpreters using the hardware XBYTE engine.
- Support for dense interpreted code, dynamic opcode tables (full 256 / compressed 16+240 etc.), persistent vs one-shot (SETQ/SETQ2), flag control from bytecodes, blending with native PASM2.
- Example VMs and optimization strategies (26M+ bytecodes/sec at 160 MHz possible).
Multi-Cog Reasoning Engine
- Model, simulate, and optimize task allocation across 8 cogs.
- Synchronization: 16 locks, events (16), COGATN attention, interrupts.
- Data flow: Hub RAM (shared, contended) vs per-cog private (CogRAM fast, LUT for XBYTE/streamer).
- Lock-free / low-contention patterns, cooperative + event-driven + interrupt-driven flows.
- Timing-aware simulation for real-time guarantees.
Memory Architecture Expertise
- Hub 512KB strategies, Cog 512L + LUT 512L, FIFO streaming (19-stage prefetch in hubexec).
- Minimize hub contention while maximizing parallelism (cogexec vs hubexec tradeoffs).
- Pointer (PTRA/PTRB) complex indexing, circular buffers, SETQ block transfers.
CORDIC Solver (Pipelined, Shared)
- Auto codegen for SIN/COS/ATAN, vector magnitude/angle (XY), hyperbolic, SQRT, LOG2/EXP2, rotations (QROTATE), scaling.
- Precise timing (55 clock latency, 8-clock issue per cog), concurrent use awareness.
Smart Pins (64 pins, 34+ modes)
- Full config for digital I/O, PWM (various), frequency, NCO, ADC (sigma-delta, SAR), serial (async, sync, USB), pulse measurement, etc.
- Autonomous peripheral management — offload cogs.
- Validation + safe mode combinations.
Cooperative Multitasking, Interrupts, Streamer, Video
- Patterns for 8-cog systems.
- 3 prioritized interrupts per cog + debug.
- Streamer (video, DAC, ADC, transport), colorspace (YUV/RGB), pixel mixer.
- Video generation scaffolding (VGA, HDMI-ish via smartpins/streamer).
Build, Compile, Hardware, Debug Orchestration
- Full support for PNut-TS (pnut_ts) cross-platform Spin2/PASM2 compiler and PNut-Term-TS (pnut-term-ts) downloader/terminal/debugger.
- Auto-detect pnut_ts / npx fallback.
- Device detection (
pnut-term-ts -l), parallel flashing of multiple USB P2 boards, coordinated test. - Safety checks, listing generation, DEBUG() support, live terminal sessions.
- Error parsing, suggestions.
Novel Paradigms Promoted
- True 8-way parallel with tiny overhead.
- Hybrid memory for lock-free designs.
- Hardware offload (XBYTE + CORDIC + Smart Pins + Streamer) to create emergent capabilities.
- Deterministic real-time "Propeller Philosophy" patterns.
Rich Context Always Available
- Best practices, idioms, perf techniques (cycle counting, scheduling).
- P2 silicon details (via deep integration with p2kb-mcp during development + embedded guidance).
- Real-time deterministic programming.
- PNut-TS / PNut-Term-TS automation + multi-device.
- Debugging multi-cog, memory safety, power/thermal.
Supports sync + streaming responses for long ops (compiles, sims, live debug).
Project Structure
P2-cookbook/
├── .fossil-settings/
│ └── ignore-glob # versioned, P2/Spin2/Python/Node aware
├── .grok/
│ ├── config.toml # project MCPs (fossil-scm-mcp + future)
│ └── skills/
│ ├── fossil-agent/ # strict Fossil VC discipline (local highest prio)
│ └── README.md
├── p2_mcp/ # The MCP server package
│ ├── __init__.py
│ ├── __main__.py
│ └── server.py # FastMCP + all @tool / @resource (P2 power tools)
├── templates/ # Spin2/PASM2 project & file templates
│ ├── p2-edge-multi-cog/
│ ├── xbyte-vm/
│ ├── cordic-dsp/
│ ├── smartpin-periph/
│ └── ...
├── examples/ # Ready-to-run demo objects + host scripts
│ ├── hello_8cogs.spin2
│ ├── xbyte_demo.spin2
│ ├── cordic_vector.spin2
│ ├── multicore_blink_pwm.spin2
│ ├── client_demo.py # example MCP client usage
│ └── ...
├── docs/
│ ├── ARCHITECTURE.md
│ ├── BEST_PRACTICES.md
│ ├── XBYTE_GUIDE.md
│ ├── MULTI_COG_PATTERNS.md
│ ├── HARDWARE_SETUP.md # P2 Edge, USB, power, multiple boards
│ └── ...
├── tests/
│ └── integration_test.py # like fossil-scm-mcp (spawns server, JSON-RPC)
├── bootstrap.sh # uv/venv + editable install (agent friendly)
├── pyproject.toml
├── README.md
└── LICENSE
The layout supports both:
- Developing the MCP server itself.
- Using the MCP to scaffold and populate real Spin2 "cookbook" projects inside or alongside.
Installation & Running the P2 Spin2 MCP (Fossil way)
Prerequisites
- Fossil SCM (>=2.20) in PATH (
fossil version) - Python >=3.10
- (Recommended)
uv - For hardware: PNut-TS / PNut-Term-TS available (via npm/npx or global
pnut_ts,pnut-term-ts). USB serial access to P2 board(s). See docs/HARDWARE_SETUP.md. - p2kb-mcp is highly recommended alongside for authoritative P2 docs (already in many envs).
Exact agent-friendly bootstrap (from public Fossil remote)
# 1. Clone with Fossil (never git)
fossil clone https://refaqtor@refaqtory.net/P2-cookbook /tmp/p2-cookbook.fossil
# 2. Open checkout
mkdir -p ~/agent-work/p2-cookbook
cd ~/agent-work/p2-cookbook
fossil open /tmp/p2-cookbook.fossil
# 3. Bootstrap (creates .venv, installs editable; .venv is ignored)
./bootstrap.sh
# 4. Run the MCP server (stdio)
.venv/bin/python -m p2_mcp
# or
.venv/bin/p2-mcp
The server will say it's starting. Configure your MCP host (Grok, Claude Desktop, Cursor, etc.) to launch it.
Example config (Grok ~/.grok/config.toml or project .grok/config.toml)
[mcp_servers.p2-mcp]
command = "/home/ben/agent-work/p2-cookbook/.venv/bin/p2-mcp"
enabled = true
startup_timeout_sec = 20
tool_timeout_sec = 180 # long compiles/sims/debug
For uv (hermetic, recommended):
[mcp_servers.p2-mcp]
command = "uv"
args = ["run", "--with-editable", ".", "--python", "3.12", "python", "-m", "p2_mcp"]
cwd = "/path/to/your/p2-cookbook/checkout"
enabled = true
Claude / Cursor / other hosts: similar stdio command pointing at the console script or python -m inside the checkout venv.
Once connected, the agent immediately has 20+ powerful P2-specific tools + resources.
Usage from an Agent
Typical flow an agent will follow (the server guides this):
- Use
p2_infoor resources for architecture refreshers. p2_scaffold_projectfor new P2 Edge multi-cog app.spin2_generate/pasm2_optimize/xbyte_createfor code.cordic_generate,smartpin_configurefor accel/periph.multicog_simulateormulticog_allocatefor 8-cog design.pnut_compile(with listing),pnut_list_devices,pnut_download(single or parallel).p2_debug_sessionor live terminal orchestration.- Profile suggestions via
p2_optimize_suggest.
All tools return LLM-optimized structured text/JSON. Many accept stream for long-running.
Resources (always available context):
p2://architecture/cogsp2://architecture/xbytep2://best-practices/hybrid-spin-pasmp2://hardware/p2-edge-pinoutp2://pnut/workflows- And more (including embedded excerpts from p2kb).
P2 Edge Hardware Setup (Quick)
See docs/HARDWARE_SETUP.md for full.
- Parallax P2 Edge Module (or P2 Eval, P2-EC, etc.)
- USB cable providing power + serial (FTDI or native).
- On Linux: user in dialout,
ls /dev/ttyUSB*or ACM. - Multiple boards: use hubs, note ports, use
-p/ specific in pnut-term-ts. - Safety: never drive pins without correct DIR, watch power/heat on overclock or heavy I/O.
- The MCP tools include validation before suggesting pin modes or downloads.
Example one-liner after scaffold:
pnut-term-ts -l # list ports
pnut_ts -l myproject.spin2
pnut-term-ts -p /dev/ttyUSB0 -d myproject.bin -t
The MCP automates all of this + multi-board + error recovery.
Example Client (Python)
See examples/client_demo.py . Rough:
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async with stdio_client(StdioServerParameters(command=".venv/bin/p2-mcp")) as (r, w):
async with ClientSession(r, w) as session:
await session.initialize()
tools = await session.list_tools()
result = await session.call_tool("spin2_generate", {"spec": "8-cog blink with lock"})
print(result)
Development of the MCP Server Itself
./bootstrap.sh
.venv/bin/python -m p2_mcp
# or for editable dev loop
uv run python -m p2_mcp
Run integration test:
.venv/bin/python tests/integration_test.py
Fossil Workflow (Mandatory)
This entire history (including how every tool and template was created) lives in Fossil.
- Inspect:
fossil status,fossil extras,fossil timeline -n 10 - Commit:
fossil commit -m "feat: ..."(always afterfossil addor with addremove) - Memory:
fossil wiki --technote now "Title" --technote-tags "phaseN,decision,xbyte" <EOF ... - At milestones: tags (
phase1-skeleton,v0.1.0) - Read FOSSIL-FOR-AGENTS.md (from fossil-scm-mcp) and the local fossil-agent skill.
The final output of this project includes the exact commands showing fossil status, fossil timeline -n 30, fossil tag list.
Status & Roadmap
Current: Full skeleton + core server + rich P2 exploitation tools + build/hardware + scaffolding + demos + docs. Production quality, heavily tested patterns from p2kb.
See Fossil timeline for the complete build log (technotes + commits tell the story).
Contributions via Fossil: clone, branch (e.g. fossil branch new feature/my-xbyte), commit, push (or bundle).
License
MIT (matching fossil-scm-mcp spirit). Parallax/Spin2/PASM2 IP respected per their licenses.
Acknowledgments
- Parallax Inc. for the Propeller 2 — the most delightful parallel microcontroller ever.
- p2kb-mcp (https://refaqtory.net/p2kb-mcp) — the authoritative, versioned knowledge base used heavily during construction.
- fossil-scm-mcp — the gold standard for agent-grade Fossil workflows.
- Chip Gracey and the P2 design team for the insane amount of cleverness in 8 cogs, XBYTE, CORDIC, Smart Pins, etc.
Start immediately with agents: clone via Fossil, bootstrap, connect the MCP, and ask it to "design an 8-cog XBYTE-based Forth VM with CORDIC accel and Smart Pin serial console for P2 Edge".
It will know exactly what to do.