PsychoPy-MCP
by weichuguang
README.md
# PsychoPy-MCP
**Controlled, auditable PsychoPy experiment design, generation, execution and quality control over the Model Context Protocol (MCP).**
PsychoPy-MCP is a local-first MCP server that lets an MCP-compatible AI agent help a researcher move from a natural-language experiment idea to a reproducible PsychoPy Coder experiment: structured configuration, balanced condition files, fixed-template script generation, static and logic validation, event-marker management, subprocess execution, behavioural data inspection and QC reports.
It is deliberately **not** a "let the model write and execute arbitrary Python" tool. The executable surface is fixed at 31 schema-validated tools; generated experiments come from audited templates and a validated configuration; a real experiment requires explicit user authorisation.
> **Version:** 0.1.0 (alpha)
> **Tested environment:** Windows 11 Pro 10.0.22621, Python 3.10.11, PsychoPy 2025.1.1, MCP Python SDK 1.30.0
> **Data policy:** local-first. No experiment data or stimulus is sent to a cloud service by the server.
---
## Highlights
- **Five experiment paradigms** — auditory oddball, visual oddball, Stroop, Go/No-Go and N-back.
- **31 MCP tools** across project, configuration, generation, validation, events, runtime, data/QC, automated testing and a protocol knowledge layer.
- **Fixed template generation** — a Coder script is rendered from a Jinja2 template and a validated config; the model never injects free-form code.
- **Balanced, reproducible conditions** — per-block allocation, recorded random seed, configurable run-length constraints, CSV/XLSX output.
- **Unified event protocol** — one `event_mapping.yaml`; codes are unique and 0–255; file/LSL/serial/parallel output adapters; hardware delivery is **never** claimed as verified.
- **Subprocess runtime** — `psychopy_start_experiment` launches a separate process, records PID/config/start time, and supports a cooperative stop before termination.
- **Behavioural QC** — inspections, event-log verification, spec-vs-output comparison, and Markdown/JSON QC reports that explicitly list checks not performed.
- **Protocol gates and claims** — 26 versioned claims and 12 method profiles; `psychopy_method_preflight` is a dry run and blocked actions are not silently retried.
- **Honest timing language** — PsychoPy software timestamps are labelled as software-clock values, not physical stimulus onsets; missing hardware verification is `not_verified`, never `PASS`.
---
## Architecture
```
MCP client (Codex, VS Code, or any MCP-compatible client)
│ JSON-RPC over stdio
▼
PsychoPy-MCP server (FastMCP)
├── Tool layer: 31 fixed tools, uniform JSON envelope
├── Experiment management layer
│ project → config → conditions → manifest → script → validation
├── Event layer
│ event_mapping.yaml → event_output.yaml → events.tsv → BIDS-style export
├── Runtime layer
│ run_spec.json → child PsychoPy process → run_state.json → logs/data
├── Data/QC layer
│ trials.csv / responses.tsv / events.tsv → QC + comparison
└── Protocol knowledge layer
claims.json + methods.json + preflight gates
│
▼
Local PsychoPy 2025.x / Python 3.10 runtime
```
A generated experiment is a normal, standalone PsychoPy Coder script. It reads `conditions.csv` in the order written, presents stimuli, writes events and responses incrementally, records a run state for the controller, and exits with a clear status.
---
## Quick start
### 1. Use a PsychoPy Python environment
PsychoPy is the runtime, so install PsychoPy-MCP into an environment that already has PsychoPy (or a virtual environment created from the PsychoPy Python with `--system-site-packages`).
Example on this machine:
```bash
cd E:\PsychoPy-MCP
D:\PsychoPy2025\python.exe -m venv --system-site-packages .venv
.venv\Scripts\python.exe -m pip install -U pip
.venv\Scripts\python.exe -m pip install -e .[dev]
```
Check the environment:
```bash
.venv\Scripts\python.exe -c "import psychopy, psychopy_mcp; print(psychopy.__version__)"
```
### 2. Edit `config/default.yaml`
At minimum, confirm:
- `paths.allowed_input_roots` — directories the server may read and create projects in.
- `paths.output_root` — where server-produced run data may be written.
- `runtime.psychopy_python` — empty means “use the interpreter running the server”; set it explicitly if the server and PsychoPy live in different environments.
### 3. Register the server with an MCP client
MCP client configuration:
```json
{
"mcpServers": {
"psychopy-mcp": {
"command": "E:\\PsychoPy-MCP\\.venv\\Scripts\\python.exe",
"args": ["-m", "psychopy_mcp.server"],
"env": {
"PSYCHOPY_MCP_CONFIG": "E:\\PsychoPy-MCP\\config\\default.yaml"
}
}
}
}
```
On macOS/Linux, use the equivalent absolute path to the virtual environment's `python`.
### 4. First conversation
Call these tools first:
1. `psychopy_get_psychopy_environment`
2. `psychopy_list_experiment_projects`
3. `psychopy_get_experiment_project` (if a project already exists)
Then follow the workflow below.
---
## Recommended workflow
```
create_experiment_project
→ create_experiment_config
→ validate_experiment_config
→ generate_condition_file
→ generate_stimulus_manifest
→ generate_psychopy_script
→ validate_psychopy_script
→ inspect_experiment_logic
→ configure_event_output
→ validate_event_mapping
→ prepare_experiment_run
→ run_experiment_preflight_test
→ run_experiment_smoke_test
→ start_experiment (authorized=true, real participant)
→ get_experiment_status / get_experiment_log
→ inspect_experiment_data
→ validate_event_log
→ generate_experiment_qc_report
→ export_bids_events
```
A real run must be authorised by the user after confirming the paradigm, timing, stimuli, event mapping and physical setup. The smoke test uses a virtual participant, shortened timings and no audio; it is an integration test, not a real experiment.
---
## The 31 tools
| Group | Tool | Purpose |
|---|---|---|
| Project | `psychopy_create_experiment_project` | Create a project directory (never overwrites). |
| Project | `psychopy_get_experiment_project` | Read metadata, structure and run list. |
| Project | `psychopy_list_experiment_projects` | List projects under allowed roots. |
| Environment | `psychopy_get_psychopy_environment` | Python/PsychoPy/module/device-probe report. |
| Config | `psychopy_create_experiment_config` | Build and validate `experiment.yaml` + event mapping. |
| Config | `psychopy_validate_experiment_config` | PASS/WARNING/FAIL checks. |
| Config | `psychopy_generate_condition_file` | Balanced `conditions.csv` / `.xlsx`. |
| Config | `psychopy_generate_stimulus_manifest` | Real file paths, sizes and SHA-256. |
| Generation | `psychopy_generate_psychopy_script` | Render the fixed Coder template. |
| Generation | `psychopy_validate_psychopy_script` | AST, pyflakes, dangerous calls, APIs, config match. |
| Generation | `psychopy_inspect_experiment_logic` | Trial/event/response/loop/overwrite checks. |
| Generation | `psychopy_generate_experiment_documentation` | Human-readable protocol document. |
| Events | `psychopy_create_event_mapping` | Unified event names/codes. |
| Events | `psychopy_validate_event_mapping` | Uniqueness, range, required events, config match. |
| Events | `psychopy_configure_event_output` | file / LSL / serial / parallel config. |
| Events | `psychopy_send_event` | Interface test only; dry-run by default. |
| Events | `psychopy_validate_event_log` | Expected vs actual events, codes, order, duplicates. |
| Events | `psychopy_export_bids_events` | BIDS-style `events.tsv`/`events.json` with explicit time-source labels. |
| Runtime | `psychopy_prepare_experiment_run` | Static preflight + `run_spec.json`; no trial executed. |
| Runtime | `psychopy_start_experiment` | Start a child process; `authorized=true` required for real runs. |
| Runtime | `psychopy_get_experiment_status` | Liveness, trial progress, state. |
| Runtime | `psychopy_stop_experiment` | Cooperative stop, then terminate; force is last resort. |
| Runtime | `psychopy_get_experiment_log` | Log tail and error lines. |
| Data/QC | `psychopy_inspect_experiment_data` | Trials, conditions, responses, RT, missing fields. |
| Data/QC | `psychopy_generate_experiment_qc_report` | Markdown + JSON QC; hardware timing is `not_verified`. |
| Data/QC | `psychopy_run_experiment_preflight_test` | Static preflight; no window/audio/child. |
| Data/QC | `psychopy_run_experiment_smoke_test` | Virtual-participant end-to-end integration test. |
| Data/QC | `psychopy_compare_experiment_spec_and_output` | Design vs actual counts/order/parameters. |
| Protocol | `psychopy_method_catalog` | 12 method profiles with checks and claims. |
| Protocol | `psychopy_protocol_claims` | 26 versioned claims with risk and source. |
| Protocol | `psychopy_method_preflight` | Dry-run protocol gates; blocked calls do not execute. |
---
## Verification status
The repository ships with 32 pytest tests (unit + synthetic QC + one real subprocess smoke test) and a protocol-level MCP client check.
Verified on the test machine:
- `pytest -q`: **32 passed**
- `ruff check src tests`: **All checks passed**
- Five example projects generate and statically validate.
- Five smoke runs (auditory oddball, visual oddball, Stroop, Go/No-Go, N-back) complete with:
- `event_validation = PASS`
- `comparison = PASS`
- `data_inspection = WARNING` (because hardware timing is `not_verified`)
- `qc = WARNING` (because hardware timing is `not_verified`)
- Official MCP Python client: `initialize`, `tools/list` (31 tools) and `tools/call` verified over stdio.
### What is **not** verified
- Physical stimulus onset measured by a photodiode or microphone.
- Audio onset measured by loopback or microphone.
- LSL/serial/parallel delivery latency and external-device receipt.
- Clock alignment with EEG/MEG/fNIRS acquisition.
- A real participant run on this machine.
- Long-duration stability or high-refresh-rate displays.
These are reported as `not_verified` and must be established by the researcher with external hardware.
---
## Supported paradigms
| Paradigm | Default events | Response rule |
|---|---|---|
| `auditory_oddball` | `STD_ONSET` 1, `DEV_ONSET` 2, `RESPONSE` 3, `BLOCK_START` 10, `BLOCK_END` 20 | respond to deviants (default space) |
| `visual_oddball` | same as auditory | respond to deviants |
| `stroop` | `CONGRUENT_ONSET` 1, `INCONGRUENT_ONSET` 2, `RESPONSE` 3, `BLOCK_START` 10, `BLOCK_END` 20 | respond by ink colour (r/g/b/y) |
| `go_nogo` | `GO_ONSET` 1, `NOGO_ONSET` 2, `RESPONSE` 3, `BLOCK_START` 10, `BLOCK_END` 20 | respond to Go, withhold to No-Go |
| `nback` | `TARGET_ONSET` 1, `NONTARGET_ONSET` 2, `RESPONSE` 3, `BLOCK_START` 10, `BLOCK_END` 20 | respond to N-back targets |
Event names and codes can be inspected with `psychopy_protocol_claims("EVENT")` and are stored in each project's `event_mapping.yaml`.
---
## Data output
Each run is written to:
```
project/
├── experiment.yaml
├── conditions.csv
├── event_mapping.yaml
├── event_output.yaml
├── stimulus_manifest.json / .csv
├── stimuli/
├── scripts/experiment.py
├── runs/
│ └── sub-001_ses-001_run-001/
│ ├── run_spec.json
│ ├── run_state.json
│ ├── controller.json
│ ├── events.tsv
│ ├── responses.tsv
│ ├── trials.csv
│ ├── experiment.log
│ ├── run_metadata.json
│ ├── event_check.json
│ ├── event_validation.json
│ ├── data_inspection.json
│ ├── spec_output_comparison.json
│ ├── qc_report.json
│ └── qc_report.md
└── docs/
├── experiment_documentation.md
└── preflight_report.json
```
The BIDS-style export adds `sub-<id>_task-<task>_events.tsv` and `.json` **inside the run directory**; this is not a complete BIDS dataset. `onset` is explicitly labelled as a PsychoPy software-clock value.
---
## Safety and scientific boundaries
1. **Fixed executable surface.** No tool accepts arbitrary Python/MATLAB/shell code. The generated script comes from a fixed template.
2. **Path allow-list.** All input/output paths are resolved to real paths and checked against configured roots.
3. **No silent overwrite.** Existing projects, configs, scripts and run data are protected; overwrite requires an explicit flag.
4. **Explicit authorisation.** A real experiment start requires `authorized=true`; the smoke test is separate.
5. **No hardware claims.** Importability of `pylsl`, `pyserial` or `psychopy.parallel` is not evidence of delivery or timing.
6. **Software timestamps are not physical onsets.** A PASS/“success” never means the timing is hardware-verified.
7. **Event semantics require researcher confirmation.** A numeric code is not a condition definition until its role is confirmed.
8. **QC reports list what they did not check.** Hardware timing, neural data quality and participant compliance are out of scope.
---
## Repository layout
```
PsychoPy-MCP/
├── pyproject.toml
├── README.md
├── LICENSE
├── config/default.yaml
├── src/psychopy_mcp/
│ ├── server.py # FastMCP registration and instructions
│ ├── config.py # validated settings
│ ├── security.py # path/name safety and hashing
│ ├── envelope.py # uniform return envelope
│ ├── methodology.py # claims + method profiles loader
│ ├── schemas/ # pydantic models
│ ├── services/ # project/config/conditions/script/events/runtime/data/QC
│ ├── templates/ # fixed Jinja2 Coder templates
│ └── data/ # claims.json, methods.json
├── skills/ # six Markdown agent skills
├── examples/ # five runnable example projects
├── tests/ # 32 pytest tests
└── docs/ # architecture, tools, event protocol, install, user guide
```
---
## Development
```bash
.venv\Scripts\python.exe -m pytest -q
.venv\Scripts\ruff.exe check src tests
```
Build:
```bash
.venv\Scripts\python.exe -m build
```
---
## Citation
If you use PsychoPy-MCP in academic work, please cite the accompanying preprint (see `preprint.md`). The software version is 0.1.0.
## License
MIT. See `LICENSE`.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessOutdated data