Compare commits
1
Commits
main
..
b09409d842
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b09409d842 |
@@ -1,52 +0,0 @@
|
|||||||
# personal-mcp MCP Usage
|
|
||||||
|
|
||||||
This repository is resource-first.
|
|
||||||
|
|
||||||
- Canonical skill guidance lives in `src/personal_mcp/docs/skills/<skill-id>/SKILL.md`.
|
|
||||||
- Skills are exposed through FastMCP's native `skill://` resource family.
|
|
||||||
- Prompts are exposed through native MCP prompt operations (`prompts/list`, `prompts/get`).
|
|
||||||
- General documentation pages are exposed through `resource://docs/{path*}`.
|
|
||||||
- The server intentionally does not provide compatibility tool projections for resources or prompts.
|
|
||||||
|
|
||||||
When a task appears to match a documented implementation pattern in `personal-mcp`, use this sequence:
|
|
||||||
|
|
||||||
1. Prefer an already attached native skill resource.
|
|
||||||
2. Otherwise browse native MCP resources and compare available `skill://<name>/SKILL.md` descriptions.
|
|
||||||
3. Read the best matching main skill file, or at most 2 candidate main files.
|
|
||||||
4. Read `skill://<name>/_manifest` only when supporting material may be useful.
|
|
||||||
5. Fetch only the relevant supporting paths from that manifest.
|
|
||||||
6. Reconcile skill guidance with the actual repository code before proposing or making changes.
|
|
||||||
|
|
||||||
Preferred MCP resource order:
|
|
||||||
|
|
||||||
1. `skill://<name>/SKILL.md`
|
|
||||||
2. `skill://<name>/_manifest` when needed
|
|
||||||
3. `skill://<name>/<supporting-path>` for selected supporting files
|
|
||||||
|
|
||||||
Selection rules:
|
|
||||||
|
|
||||||
- Prefer the closest `name` and `description` match.
|
|
||||||
- Keep context bounded; do not load many skill documents speculatively.
|
|
||||||
- If confidence is low after reading at most two main files, ask one clarifying question before loading more context.
|
|
||||||
|
|
||||||
Repository-specific guidance:
|
|
||||||
|
|
||||||
- For tasks about adding or modifying a skill, use `skill://copilot-customization/SKILL.md` when relevant.
|
|
||||||
- Keep skills provider-native; do not add tool projections for resource or prompt access.
|
|
||||||
|
|
||||||
|
|
||||||
## Python Checks
|
|
||||||
|
|
||||||
After changes run these commands to confirm functionality. Resolve any errors
|
|
||||||
|
|
||||||
```python
|
|
||||||
uv run ruff check .
|
|
||||||
```
|
|
||||||
|
|
||||||
```python
|
|
||||||
uv run ty check
|
|
||||||
```
|
|
||||||
|
|
||||||
```python
|
|
||||||
uv run pytest
|
|
||||||
```
|
|
||||||
@@ -1,19 +1,17 @@
|
|||||||
---
|
---
|
||||||
name: Authoring Content
|
name: Authoring Content
|
||||||
description: "Use when editing Markdown under src/personal_mcp/docs/. Routes authors to the canonical docs ownership and layout guidance."
|
description: "Use when editing Markdown under docs/. Routes authors to the canonical docs ownership, layout, and symlink guidance."
|
||||||
applyTo: 'src/personal_mcp/docs/**/*.md'
|
applyTo: 'docs/**/*.md'
|
||||||
---
|
---
|
||||||
|
|
||||||
For edits under `src/personal_mcp/docs/`, use the [Authoring Guide](../../src/personal_mcp/docs/authoring.md) as the entry point for content placement and contracts.
|
For edits under `docs/`, use the [Authoring Guide](../../docs/authoring.md) as the entry point for content placement and contracts.
|
||||||
|
|
||||||
For source-tree ownership, packaging, or runtime questions, follow [Source Tree Ownership](../../src/personal_mcp/docs/authoring.md). Treat that section as authoritative instead of restating its guidance here.
|
For source-tree ownership, symlink, packaging, or runtime questions, follow [Source Tree Ownership](../../docs/authoring.md). Treat that section as authoritative instead of restating its guidance here.
|
||||||
|
|
||||||
|
|
||||||
Primary references:
|
Primary references:
|
||||||
- [Skill contract](../../src/personal_mcp/docs/contracts/skill_contract.md)
|
- [Skill contract](../../docs/contracts/skill_contract.md)
|
||||||
- [Prompt contract](../../src/personal_mcp/docs/contracts/prompt.md)
|
- [Prompt contract](../../docs/contracts/prompt.md)
|
||||||
- [Frontmatter contract](../../src/personal_mcp/docs/contracts/frontmatter.md)
|
- [Frontmatter contract](../../docs/contracts/frontmatter.md)
|
||||||
- [URI contract](../../src/personal_mcp/docs/contracts/uris.md)
|
- [URI contract](../../docs/contracts/uris.md)
|
||||||
- `skill://zensical-docs/SKILL.md`
|
- [Zensical documentation authoring skill](../../docs/skills/zensical-docs/SKILL.md)
|
||||||
|
|
||||||
Inspect `skill://zensical-docs/_manifest` only when a supporting documentation reference is needed.
|
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
---
|
|
||||||
name: FastMCP Python Guidance
|
|
||||||
description: Route FastMCP Python changes to the Personal MCP source-reference skill.
|
|
||||||
applyTo: '**/*.py'
|
|
||||||
---
|
|
||||||
|
|
||||||
A core part of this repository is [FastMCP](https://gofastmcp.com/servers/server).
|
|
||||||
|
|
||||||
For FastMCP implementation or protocol questions, load `skill://mcp-details/SKILL.md` first.
|
|
||||||
|
|
||||||
Inspect `skill://mcp-details/_manifest` only when a source reference is needed, then read the relevant supporting path. For FastMCP Python APIs, prefer the supporting reference that covers SDKs and FastMCP.
|
|
||||||
|
|
||||||
This repository exposes skills through native MCP resources and prompts through native MCP prompt operations.
|
|
||||||
|
|
||||||
Reconcile the skill guidance with the installed FastMCP version and the repository's existing implementation before editing.
|
|
||||||
@@ -1,24 +1,18 @@
|
|||||||
---
|
---
|
||||||
name: Pytest Scaffolding Guidance
|
name: Pytest Scaffolding Guidance
|
||||||
description: Use when working under tests/. Route test edits to pytesting guidance and never create or expand tests unless the user explicitly asks.
|
description: Route tests edits to the Personal MCP pytesting resource.
|
||||||
applyTo: 'tests/**'
|
applyTo: 'tests/**'
|
||||||
---
|
---
|
||||||
|
|
||||||
When editing files under `tests/`, use `skill://pytesting/SKILL.md` as the primary guidance source for test scaffolding and pytest authoring decisions.
|
When editing files under `tests/`, use `resource://skills/pytesting/document` as the primary guidance source for test scaffolding and pytest authoring decisions.
|
||||||
|
|
||||||
Hard rule:
|
|
||||||
|
|
||||||
- Do not create new test files, test cases, or test scaffolding unless the user explicitly asks for tests in the current request.
|
|
||||||
- If tests could help but were not requested, mention them as an optional next step instead of adding them.
|
|
||||||
|
|
||||||
Execution pattern:
|
Execution pattern:
|
||||||
|
|
||||||
1. Load `skill://pytesting/SKILL.md` first.
|
1. Load `resource://skills/pytesting/document` first.
|
||||||
2. Inspect `skill://pytesting/_manifest` only when a supporting reference is needed.
|
2. Apply only the portions relevant to the file being edited.
|
||||||
3. Apply only the portions relevant to the file being edited.
|
3. Keep tests focused, deterministic, and aligned with repository conventions.
|
||||||
4. Keep tests focused, deterministic, and aligned with repository conventions.
|
4. Include source-document links for any feature-level recommendation.
|
||||||
5. Include source-document links for any feature-level recommendation.
|
|
||||||
|
|
||||||
If task intent is ambiguous, ask one clarifying question before editing.
|
If task intent is ambiguous, ask one clarifying question before editing.
|
||||||
|
|
||||||
Be sure to also refer to the [testing page](../../src/personal_mcp/docs/testing.md) for design detail.
|
Be sure to also refer to the [testing page](../../docs/testing.md) page for design detail
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
---
|
|
||||||
name: Skill Authoring
|
|
||||||
description: "Use when creating or editing skills under src/personal_mcp/docs/skills/. Enforces the Agent Skills specification and FastMCP skill provider compatibility."
|
|
||||||
applyTo: 'src/personal_mcp/docs/skills/**'
|
|
||||||
---
|
|
||||||
|
|
||||||
# Skill Authoring
|
|
||||||
|
|
||||||
Before editing files under `src/personal_mcp/docs/skills/`, consult all of these references:
|
|
||||||
|
|
||||||
- [Agent Skills quickstart](https://agentskills.io/skill-creation/quickstart)
|
|
||||||
- [Agent Skills best practices](https://agentskills.io/skill-creation/best-practices)
|
|
||||||
- [FastMCP skill providers](https://gofastmcp.com/servers/providers/skills)
|
|
||||||
|
|
||||||
Treat each immediate subdirectory of `src/personal_mcp/docs/skills/` as an independent Agent Skill. Keep its structure and content compliant with the Agent Skills pattern and compatible with the FastMCP skill provider.
|
|
||||||
|
|
||||||
Reconcile the external guidance with the repository's existing skill conventions and contracts before making changes.
|
|
||||||
@@ -4,12 +4,12 @@ description: Route .vscode edits to the Personal MCP VS Code configuration skill
|
|||||||
applyTo: '.vscode/**'
|
applyTo: '.vscode/**'
|
||||||
---
|
---
|
||||||
|
|
||||||
When editing files under `.vscode/`, use `skill://vscode-configuration/SKILL.md` as the primary guidance source.
|
When editing files under `.vscode/`, use `resource://skills/vscode-configuration/document` as the primary guidance source.
|
||||||
|
|
||||||
Execution pattern:
|
Execution pattern:
|
||||||
|
|
||||||
1. Load `skill://vscode-configuration/SKILL.md` first.
|
1. Load `resource://skills/vscode-configuration/document` first.
|
||||||
2. Inspect `skill://vscode-configuration/_manifest` and select only the matching reference page for the current file type:
|
2. Select only the matching reference page for the current file type:
|
||||||
- `launch.json` -> debug launch configurations.
|
- `launch.json` -> debug launch configurations.
|
||||||
- `tasks.json` -> tasks.json project tasks.
|
- `tasks.json` -> tasks.json project tasks.
|
||||||
- `mcp.json` -> mcp.json MCP server configuration.
|
- `mcp.json` -> mcp.json MCP server configuration.
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ description: Use the Zensical docs MCP resource when editing Markdown documentat
|
|||||||
applyTo: '**/*.md'
|
applyTo: '**/*.md'
|
||||||
---
|
---
|
||||||
|
|
||||||
When editing Markdown files in this repository, use `skill://zensical-docs/SKILL.md` for relevant documentation authoring guidance. Inspect `skill://zensical-docs/_manifest` only when a supporting reference is needed.
|
When editing Markdown files in this repository, use the Zensical docs resource `resource://skills/zensical-docs/document` for relevant documentation authoring guidance.
|
||||||
|
|
||||||
Prefer Zensical-native documentation conventions when they cover the need cleanly, while preserving expected MkDocs compatibility unless the Zensical guidance intentionally diverges.
|
Prefer Zensical-native documentation conventions when they cover the need cleanly, while preserving expected MkDocs compatibility unless the Zensical guidance intentionally diverges.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
## Plan: Docs-First FastMCP End State
|
||||||
|
|
||||||
|
Create a docs-first FastMCP architecture where all Markdown remains in docs/ as the only source of truth, each skill is Anthropic-compatible in its own directory, skill metadata lives in SKILL.md frontmatter, and packaged docs are served through importlib.resources so stdio deployments work from installed wheels.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
1. Phase 1: Define the end-state content contract. Confirm canonical structure as docs/skills/<skill-id>/SKILL.md plus docs/skills/<skill-id>/references/..., with strict per-skill ownership and no metadata.yaml sidecar. Also define stable skill-id rules (kebab-case, immutable after release). Deliverable: update the current docs/ directory with the finalized end-state content contract from this step.
|
||||||
|
2. Phase 1: Define SKILL.md frontmatter schema with Pydantic-compatible fields: id, version, name, description, tags, capabilities, depends_on, and references manifest entries. The references manifest must map logical reference ids to relative paths so each skill can reorganize references internally without changing global server code. Depends on step 1. Deliverable: update the current docs/ directory with the finalized SKILL.md frontmatter schema from this step.
|
||||||
|
3. Phase 1: Define URI contract with explicit break-and-replace policy. Recommend resource://catalog/skills_index, resource://catalog/skills/{skill_id}, resource://skills/{skill_id}/document, resource://skills/{skill_id}/references/{ref_id}, and resource://docs/{path*}. Evolving URIs and reference ids requires direct replacement, with no aliases or compatibility shims. Depends on steps 1-2. Deliverable: update the current docs/ directory with the finalized URI contract and break-and-replace policy from this step.
|
||||||
|
4. Phase 2: Build a docs registry loader that reads packaged docs via importlib.resources.files(...) Traversable APIs, parses SKILL.md frontmatter, validates schema, and creates an in-memory registry keyed by skill_id. Fail fast for duplicate ids, missing files, broken reference mappings, or invalid depends_on. Depends on steps 2-3.
|
||||||
|
5. Phase 2: Register FastMCP resources from the registry using RFC6570 templates (including wildcard paths where appropriate), read-only/idempotent annotations, explicit mime types, and on_duplicate_resources="error" for startup safety. Depends on step 4.
|
||||||
|
6. Phase 2: Add discovery surfaces as resources first, then tool fallback. Keep catalog discovery in resources, then add ResourcesAsTools for tool-only clients. Add thin discovery tools only for parity and optional BM25/regex tool search when catalog/tool volume grows enough to affect token efficiency. Define canonical fallback tool names (`list_resources`, `read_resource`, `search_patterns`, `get_pattern_by_id`, `get_skill_document_by_id`), research host-specific naming behavior for GitHub Copilot, Cursor, Claude Desktop, and generic MCP clients, and require client-side name mapping or intentionally documented aliases when providers expose namespaced wrappers. Depends on step 5.
|
||||||
|
7. Phase 3: Implement packaging so docs/ is copied into package resource space at build time (wheel + sdist) while docs/ remains canonical in source control. Use importlib.resources at runtime only; avoid direct filesystem assumptions. Depends on steps 4-6.
|
||||||
|
8. Phase 3: Remove materialization coupling between skill source modules and docs. The website build reads docs/ directly, while MCP reads packaged docs resources from the installed package. This preserves one authored source with two distribution surfaces. Depends on step 7.
|
||||||
|
9. Phase 4: Add validation and CI gates: frontmatter schema checks, URI uniqueness checks, reference integrity checks, docs build check, package content check, and stdio smoke checks that read representative skill/document resources from an installed wheel. Depends on steps 5-8.
|
||||||
|
10. Phase 4: Add long-term maintainability guardrails: architecture decision record for URI and schema contracts, skill authoring checklist, and release checklist for evolving references safely within one skill. Parallel with step 9 after core architecture is stable.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
**Relevant files**
|
||||||
|
- /home/john/Documents/prompts/docs/index.md — Keep top-level docs entry and explain docs-first architecture contract.
|
||||||
|
- /home/john/Documents/prompts/docs/skills — Canonical location for all skill content, including SKILL.md and references.
|
||||||
|
- /home/john/Documents/prompts/pyproject.toml — Build inclusion rules for packaged markdown resources in wheel/sdist.
|
||||||
|
- /home/john/Documents/prompts/src/personal_mcp/main.py — App/server startup wiring for resource registry initialization.
|
||||||
|
- /home/john/Documents/prompts/src/personal_mcp/mcp.py — FastMCP instance composition and transform registration.
|
||||||
|
- /home/john/Documents/prompts/src/personal_mcp/catalog/server.py — Catalog resource and fallback discovery behavior.
|
||||||
|
- /home/john/Documents/prompts/src/personal_mcp/skills/document_loader.py — Replace file-path assumptions with importlib.resources docs registry loading.
|
||||||
|
- /home/john/Documents/prompts/src/personal_mcp/web/materialize_skill_docs.py — De-scope or retire materialization once docs-first runtime is authoritative.
|
||||||
|
|
||||||
|
**Verification**
|
||||||
|
1. Run uv run zensical build to verify docs/ remains valid and site output is stable.
|
||||||
|
2. Run uv run pytest -q with tests that validate frontmatter parsing, URI generation, reference mapping, and catalog responses.
|
||||||
|
3. Run a packaging integrity check using importlib.resources.files(...) to confirm packaged docs resources exist and are readable from an installed wheel.
|
||||||
|
4. Run a stdio MCP smoke test that lists resources and reads at least one skill document and one reference document.
|
||||||
|
5. Run fallback-client smoke tests verifying list_resources/read_resource tools work and return expected metadata for both static and templated resources, and that GitHub Copilot, Cursor, Claude Desktop, and protocol-level SDK tests use canonical tool names or documented mapped aliases.
|
||||||
|
|
||||||
|
**Decisions**
|
||||||
|
- Anthropic compatibility: strict skill directory pattern with SKILL.md and references subtree.
|
||||||
|
- Metadata strategy: YAML frontmatter in SKILL.md (no separate metadata file).
|
||||||
|
- Discovery strategy: resource-first catalog with tool fallback for tool-only MCP clients.
|
||||||
|
- Included scope: ideal end-state architecture, contracts, validation, and packaging for stdio operation.
|
||||||
|
- Excluded scope: migration mechanics from current implementation, backward-compat shim details, and docs visual redesign.
|
||||||
|
|
||||||
|
**Further Considerations**
|
||||||
|
1. Prefer recursive references support under each skill plus frontmatter manifest ids, so skill teams can reorganize internal reference folders without URI churn.
|
||||||
|
2. Define a hard rule that skill_id and directory name must match exactly to eliminate namespace/slug drift classes of bugs.
|
||||||
|
3. Do not provide URI aliases; client updates must track canonical URI contract changes directly.
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
**Phase 3 Results: Packaging Contract and Surface Decoupling (Wheel/sdist Resources + Docs-Only Authoring)**
|
||||||
|
|
||||||
|
This section finalizes Phase 3 by defining how authored docs are packaged as runtime resources, how runtime loading avoids filesystem assumptions, and how website and MCP distribution surfaces are decoupled while sharing one authored source.
|
||||||
|
|
||||||
|
### Greenfield Framing (Normative)
|
||||||
|
|
||||||
|
This Phase 3 design assumes a full refactor with intentional break-and-replace behavior:
|
||||||
|
|
||||||
|
1. No compatibility shims, aliases, adapter layers, or dual-read runtime paths.
|
||||||
|
2. No runtime dependency on repository checkout layout.
|
||||||
|
3. Runtime docs access is package-resource-only.
|
||||||
|
4. Canonical authoring remains in `docs/` in source control.
|
||||||
|
|
||||||
|
### Research Baseline (Packaging + Runtime)
|
||||||
|
|
||||||
|
Authoritative references used for this phase:
|
||||||
|
|
||||||
|
1. Python `importlib.resources` docs (`files`, `Traversable`, and zip-safe behavior)
|
||||||
|
2. Python packaging guidance for wheel/sdist data inclusion
|
||||||
|
3. Hatchling build target configuration guidance for including non-code files
|
||||||
|
4. Existing repository constraints from Steps 4-5 (registry-first, deterministic startup, resource-first discovery)
|
||||||
|
|
||||||
|
Best-practice conclusions applied to this design:
|
||||||
|
|
||||||
|
1. Package docs as build artifacts so runtime reads work from installed wheels.
|
||||||
|
2. Keep docs source-of-truth in one place (`docs/`) and project into package resource space at build time.
|
||||||
|
3. Avoid `Path(__file__)`/repo-root probing in runtime paths.
|
||||||
|
4. Enforce parity across wheel and sdist so local/dev/prod behavior does not drift.
|
||||||
|
|
||||||
|
### Phase 3 Responsibilities (Normative)
|
||||||
|
|
||||||
|
Phase 3 MUST:
|
||||||
|
|
||||||
|
1. Ensure authored markdown under `docs/` is included in wheel and sdist artifacts.
|
||||||
|
2. Ensure runtime docs registry/document reads use `importlib.resources` only.
|
||||||
|
3. Ensure MCP runtime behavior is independent of current working directory or checkout structure.
|
||||||
|
4. Ensure website docs build continues to consume source `docs/` directly.
|
||||||
|
5. Remove materialization/path-probing coupling from runtime loader code.
|
||||||
|
6. Preserve deterministic packaged docs layout for registry/resource URI generation.
|
||||||
|
|
||||||
|
### Packaging Contract (Wheel + sdist)
|
||||||
|
|
||||||
|
Canonical packaging behavior:
|
||||||
|
|
||||||
|
1. Source-authored docs remain at repository root: `docs/`.
|
||||||
|
2. Build projects docs into package resource space under `personal_mcp/docs/` inside artifacts.
|
||||||
|
3. Runtime anchor for docs loading is `importlib.resources.files("personal_mcp").joinpath("docs")`.
|
||||||
|
4. Build artifacts MUST include:
|
||||||
|
- top-level docs pages used by discovery/overview
|
||||||
|
- `docs/skills/<skill-id>/SKILL.md`
|
||||||
|
- `docs/skills/<skill-id>/references/**`
|
||||||
|
|
||||||
|
Parity requirements:
|
||||||
|
|
||||||
|
1. Wheel and sdist contain equivalent docs content for runtime use.
|
||||||
|
2. Missing docs resources in either artifact is a hard validation failure.
|
||||||
|
|
||||||
|
### Build-System Plan (pyproject + build)
|
||||||
|
|
||||||
|
Primary target file:
|
||||||
|
|
||||||
|
1. `pyproject.toml`
|
||||||
|
|
||||||
|
Configuration goals:
|
||||||
|
|
||||||
|
1. Add explicit build inclusion rules so docs resources are shipped in wheel artifacts.
|
||||||
|
2. Add explicit sdist inclusion rules so docs are present for source builds.
|
||||||
|
3. Keep inclusion deterministic and auditable (no implicit glob side effects beyond intended docs content).
|
||||||
|
4. Ensure packaged destination path matches runtime anchor (`personal_mcp/docs`).
|
||||||
|
|
||||||
|
Implementation note:
|
||||||
|
|
||||||
|
1. Use Hatchling-native inclusion mapping (for example force-include or equivalent target-level include mapping) to project `docs/` into package resource space.
|
||||||
|
2. Prefer one clear packaging path over multiple fallback packaging mechanisms.
|
||||||
|
|
||||||
|
### Runtime Loader Contract (No Filesystem Assumptions)
|
||||||
|
|
||||||
|
Primary target file:
|
||||||
|
|
||||||
|
1. `src/personal_mcp/skills/document_loader.py`
|
||||||
|
|
||||||
|
Required runtime behavior:
|
||||||
|
|
||||||
|
1. Remove repository-root discovery helpers and path-probing candidates.
|
||||||
|
2. Remove metadata-based document path overrides that bypass canonical skill layout.
|
||||||
|
3. Resolve SKILL and reference documents via package-resource-relative paths only.
|
||||||
|
4. Keep reads UTF-8 and deterministic.
|
||||||
|
5. Raise explicit errors for missing packaged resources; no fallback probing.
|
||||||
|
|
||||||
|
Prohibited runtime behavior:
|
||||||
|
|
||||||
|
1. No `Path(__file__).resolve().parents[...]` lookup for docs.
|
||||||
|
2. No implicit fallback to source-tree `docs/` during runtime reads.
|
||||||
|
3. No slug-guessing or namespace substitution for path recovery.
|
||||||
|
|
||||||
|
### Surface Decoupling Contract (Website vs MCP)
|
||||||
|
|
||||||
|
Website surface:
|
||||||
|
|
||||||
|
1. Website build pipeline consumes source `docs/` directly (`uv run zensical build`).
|
||||||
|
2. Static output (`site/`) remains a build artifact served by web mounting logic.
|
||||||
|
|
||||||
|
MCP surface:
|
||||||
|
|
||||||
|
1. MCP runtime serves docs from packaged resources loaded by registry/resource handlers.
|
||||||
|
2. MCP does not read `site/` and does not depend on website build artifacts.
|
||||||
|
|
||||||
|
Decoupling guarantees:
|
||||||
|
|
||||||
|
1. One authored source (`docs/`), two distribution surfaces (website + MCP runtime).
|
||||||
|
2. Changes to website serving do not alter MCP resource loading semantics.
|
||||||
|
3. Changes to MCP runtime loader do not require website materialization logic.
|
||||||
|
|
||||||
|
### Integration Plan for Existing Modules
|
||||||
|
|
||||||
|
Primary integration targets:
|
||||||
|
|
||||||
|
1. `pyproject.toml`: add wheel/sdist docs inclusion mapping.
|
||||||
|
2. `src/personal_mcp/skills/document_loader.py`: replace filesystem probing with package-resource loading.
|
||||||
|
3. `src/personal_mcp/main.py`: keep startup composition deterministic once registry/resource registration is in place.
|
||||||
|
4. `src/personal_mcp/mcp.py`: maintain registry-driven resource composition as canonical runtime surface.
|
||||||
|
5. `src/personal_mcp/web/docs_mount.py`: continue static-site mount behavior without coupling to MCP runtime docs loading.
|
||||||
|
|
||||||
|
Cleanup targets:
|
||||||
|
|
||||||
|
1. Remove obsolete references to materialization-only modules if no longer present/used.
|
||||||
|
2. Remove dead code paths that attempt source-tree fallback loading.
|
||||||
|
|
||||||
|
### Validation and Test Plan (Phase 3 Scope)
|
||||||
|
|
||||||
|
Build/package validation:
|
||||||
|
|
||||||
|
1. Build wheel and sdist in CI/local.
|
||||||
|
2. Inspect artifacts to confirm `personal_mcp/docs/**` exists and includes representative skill/reference files.
|
||||||
|
3. Install built wheel in isolated environment and verify resource reads via `importlib.resources.files(...)`.
|
||||||
|
|
||||||
|
Runtime validation:
|
||||||
|
|
||||||
|
1. Run MCP in an environment where repo-root docs paths are unavailable and confirm reads still succeed.
|
||||||
|
2. Verify representative URIs resolve (skill document and reference document).
|
||||||
|
3. Confirm startup fails clearly if required packaged docs resources are missing.
|
||||||
|
|
||||||
|
Decoupling validation:
|
||||||
|
|
||||||
|
1. Run `uv run zensical build` to verify website pipeline still consumes source `docs/`.
|
||||||
|
2. Confirm MCP runtime does not require `site/` presence.
|
||||||
|
3. Confirm web static serving behavior is unchanged when docs are built.
|
||||||
|
|
||||||
|
Expected command path in this repo:
|
||||||
|
|
||||||
|
1. `uv run pytest -q`
|
||||||
|
2. `uv run zensical build`
|
||||||
|
|
||||||
|
### Acceptance Criteria for Phase 3 Completion
|
||||||
|
|
||||||
|
Phase 3 is complete when all are true:
|
||||||
|
|
||||||
|
1. Wheel and sdist include docs resources in deterministic package paths.
|
||||||
|
2. Runtime docs loading works from installed artifacts using `importlib.resources` only.
|
||||||
|
3. Runtime docs loading has no checkout-path dependency and no fallback probing.
|
||||||
|
4. Website docs build remains source-docs-driven and independent of MCP runtime loading.
|
||||||
|
5. No compatibility shims, aliases, or dual runtime loader paths exist.
|
||||||
|
|
||||||
|
### Non-goals for Phase 3
|
||||||
|
|
||||||
|
1. No Step 6 discovery-tool fallback implementation details.
|
||||||
|
2. No URI aliasing or backward-compat transition mechanics.
|
||||||
|
3. No redesign of skill frontmatter/schema contracts already finalized in earlier steps.
|
||||||
|
4. No web UI visual redesign or docs IA overhaul.
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
**Step 1 Results: End-State Content Contract**
|
||||||
|
|
||||||
|
This section finalizes Step 1 by defining the canonical authored content model.
|
||||||
|
|
||||||
|
### Step Deliverable
|
||||||
|
|
||||||
|
- Update the current `docs/` directory with the finalized Step 1 content contract from this document.
|
||||||
|
|
||||||
|
### Canonical source of truth
|
||||||
|
|
||||||
|
- All authored Markdown lives under `docs/`.
|
||||||
|
- MCP resources and static docs are two distribution surfaces of the same authored files.
|
||||||
|
- No parallel authored markdown is allowed in `src/` or other package-only paths.
|
||||||
|
|
||||||
|
### Canonical skill shape (Anthropic-compatible)
|
||||||
|
|
||||||
|
Each skill is one directory under `docs/skills/`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/
|
||||||
|
skills/
|
||||||
|
<skill-id>/
|
||||||
|
SKILL.md
|
||||||
|
references/
|
||||||
|
... (one or more markdown files, optional nested folders)
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- `SKILL.md` is required for every skill.
|
||||||
|
- `references/` is the only place for skill-specific supporting docs.
|
||||||
|
- Nested folders inside `references/` are allowed so a skill can reorganize internals without changing global architecture.
|
||||||
|
- Skill directories are independent ownership boundaries; no cross-skill file writes.
|
||||||
|
|
||||||
|
### File placement and ownership boundaries
|
||||||
|
|
||||||
|
- Top-level project docs stay in `docs/*.md`.
|
||||||
|
- Skill docs stay in `docs/skills/<skill-id>/...`.
|
||||||
|
- A skill may link to other skills, but must not store content inside another skill's directory.
|
||||||
|
- Server/runtime code may index and serve docs, but must not be the source of authored markdown.
|
||||||
|
|
||||||
|
### Metadata location constraint
|
||||||
|
|
||||||
|
- Skill metadata is embedded in YAML frontmatter in `SKILL.md`.
|
||||||
|
- No `metadata.yaml` sidecar in the end state.
|
||||||
|
- Reference lookup metadata (ids to relative paths) is declared from `SKILL.md` frontmatter, not inferred as a hidden global convention.
|
||||||
|
|
||||||
|
### Skill-id contract (change-friendly)
|
||||||
|
|
||||||
|
`skill-id` is the public identifier and SHOULD satisfy all rules below:
|
||||||
|
|
||||||
|
- Format: lowercase kebab-case only.
|
||||||
|
- Character set: `a-z`, `0-9`, and `-`.
|
||||||
|
- Must start with a letter.
|
||||||
|
- No underscores, spaces, dots, or uppercase characters.
|
||||||
|
- Directory name should equal `skill-id` in each committed revision.
|
||||||
|
- Frontmatter `id` should equal directory name in each committed revision.
|
||||||
|
- Treat `skill-id` as immutable after release; any rename is a breaking replacement and clients must move to the new id.
|
||||||
|
|
||||||
|
Example valid ids:
|
||||||
|
|
||||||
|
- `fastapi-uv-docker`
|
||||||
|
- `zensical-docs`
|
||||||
|
- `pytesting`
|
||||||
|
|
||||||
|
Example invalid ids:
|
||||||
|
|
||||||
|
- `fastapi_uv_docker` (underscore)
|
||||||
|
- `Zensical-Docs` (uppercase)
|
||||||
|
- `docs.zensical` (dot)
|
||||||
|
|
||||||
|
### Invariants this contract guarantees
|
||||||
|
|
||||||
|
- One authored source tree (`docs/`) for both website and MCP.
|
||||||
|
- One skill directory maps to one skill identity per revision.
|
||||||
|
- Namespace/slug drift is minimized by keeping directory and frontmatter ids aligned per revision.
|
||||||
|
- Per-skill reference structure can evolve without changing cross-skill architecture.
|
||||||
|
- Packaging for stdio is deterministic because authored content is path-stable.
|
||||||
|
|
||||||
|
### Non-goals for Step 1
|
||||||
|
|
||||||
|
- No URI versioning policy details yet (handled in Step 3).
|
||||||
|
- No full frontmatter schema details yet (handled in Step 2).
|
||||||
|
- No migration instructions from current architecture (out of scope for this plan).
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
**Step 2 Results: SKILL.md Frontmatter and FastMCP Metadata Contract**
|
||||||
|
|
||||||
|
This section finalizes Step 2 by defining the canonical SKILL.md frontmatter schema, separating Anthropic-supported fields from repository extension fields, and mapping frontmatter to FastMCP-native metadata surfaces for resources and tools.
|
||||||
|
|
||||||
|
### Step Deliverable
|
||||||
|
|
||||||
|
- Update the current `docs/` directory with the finalized Step 2 frontmatter and metadata contract content from this document.
|
||||||
|
|
||||||
|
### Anthropic Frontmatter Support (Research Baseline)
|
||||||
|
|
||||||
|
Across Anthropic API and Agent Skills specification surfaces:
|
||||||
|
|
||||||
|
- Required for custom skill bundles: `name`, `description`.
|
||||||
|
- `name` constraints (Agent Skills API docs): 1-64 chars, lowercase letters/numbers/hyphens, no XML tags, and must not use reserved words `anthropic` or `claude`.
|
||||||
|
- `description` constraints (Agent Skills API docs): 1-1024 chars, non-empty, no XML tags.
|
||||||
|
|
||||||
|
Portable optional fields from the Agent Skills specification:
|
||||||
|
|
||||||
|
- `license`
|
||||||
|
- `compatibility`
|
||||||
|
- `metadata`
|
||||||
|
- `allowed-tools` (experimental)
|
||||||
|
|
||||||
|
Claude Code-specific optional fields (supported by Claude Code skills docs):
|
||||||
|
|
||||||
|
- `when_to_use`, `argument-hint`, `arguments`
|
||||||
|
- `disable-model-invocation`, `user-invocable`
|
||||||
|
- `allowed-tools`, `disallowed-tools`
|
||||||
|
- `model`, `effort`, `context`, `agent`, `hooks`, `paths`, `shell`
|
||||||
|
|
||||||
|
Contract decision for this repository:
|
||||||
|
|
||||||
|
- Treat `name` and `description` as required in all SKILL.md files, even where a client could infer defaults.
|
||||||
|
- Keep Anthropic-facing semantics in standard fields and keep MCP indexing metadata in a namespaced extension block.
|
||||||
|
- Preserve forward compatibility by allowing additive optional metadata fields over time.
|
||||||
|
|
||||||
|
### Canonical Frontmatter Schema For This Repository
|
||||||
|
|
||||||
|
Use this exact two-layer pattern:
|
||||||
|
|
||||||
|
1. Anthropic layer (portable): top-level fields intended for Anthropic/Agent Skills behavior.
|
||||||
|
2. Repository layer (runtime indexing): one namespaced block, `x-personal-mcp`, for MCP catalog and routing metadata.
|
||||||
|
|
||||||
|
Canonical shape:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
name: <skill-id>
|
||||||
|
description: <what this skill does and when to use it>
|
||||||
|
|
||||||
|
# Optional Anthropic/Agent Skills fields (use only when needed)
|
||||||
|
when_to_use: <extra trigger guidance>
|
||||||
|
allowed-tools: <space-separated string or YAML list>
|
||||||
|
disable-model-invocation: false
|
||||||
|
user-invocable: true
|
||||||
|
license: <optional>
|
||||||
|
compatibility: <optional>
|
||||||
|
|
||||||
|
# Repository-specific metadata (authoritative for MCP indexing)
|
||||||
|
x-personal-mcp:
|
||||||
|
id: <skill-id>
|
||||||
|
version: <semver>
|
||||||
|
tags:
|
||||||
|
- <tag>
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/<skill-id>/document
|
||||||
|
depends_on: []
|
||||||
|
references:
|
||||||
|
<ref-id>:
|
||||||
|
path: references/<file>.md
|
||||||
|
mime_type: text/markdown
|
||||||
|
title: <short title>
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
### Repository Metadata Field Rules (`x-personal-mcp`)
|
||||||
|
|
||||||
|
- `id` required: must follow Step 1 skill-id rules and equal directory name.
|
||||||
|
- `version` required: semantic version string.
|
||||||
|
- `tags` optional: list of kebab-case discovery labels.
|
||||||
|
- `capabilities` required: list of MCP URIs this skill publishes.
|
||||||
|
- `depends_on` optional: list of other skill ids.
|
||||||
|
- `references` optional map:
|
||||||
|
- key is `ref-id` (kebab-case).
|
||||||
|
- `path` is a skill-relative markdown path and must stay inside the same skill directory.
|
||||||
|
- nested folders under `references/` are allowed.
|
||||||
|
- `mime_type` defaults to `text/markdown` if omitted.
|
||||||
|
- `title` is an optional display label.
|
||||||
|
- renaming `ref-id` values is allowed when needed; optional aliases may be used during transitions.
|
||||||
|
|
||||||
|
### Pydantic Models For Frontmatter Validation
|
||||||
|
|
||||||
|
Define the Step 2 contract with Pydantic v2 models and change-friendly validation.
|
||||||
|
|
||||||
|
Normative model sketch:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from pathlib import PurePosixPath
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||||
|
|
||||||
|
SKILL_ID_RE = re.compile(r"^[a-z][a-z0-9-]*$")
|
||||||
|
SEMVER_RE = re.compile(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:[-+][0-9A-Za-z.-]+)?$")
|
||||||
|
|
||||||
|
|
||||||
|
class ReferenceEntry(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="ignore", str_strip_whitespace=True)
|
||||||
|
|
||||||
|
path: str
|
||||||
|
mime_type: str = "text/markdown"
|
||||||
|
title: str | None = None
|
||||||
|
|
||||||
|
@field_validator("path")
|
||||||
|
@classmethod
|
||||||
|
def validate_reference_path(cls, value: str) -> str:
|
||||||
|
p = PurePosixPath(value)
|
||||||
|
if p.is_absolute() or ".." in p.parts:
|
||||||
|
raise ValueError("reference path must be a relative in-skill path")
|
||||||
|
if not str(p).startswith("references/"):
|
||||||
|
raise ValueError("reference path must stay under references/")
|
||||||
|
if p.suffix.lower() != ".md":
|
||||||
|
raise ValueError("reference path must target a markdown file")
|
||||||
|
return str(p)
|
||||||
|
|
||||||
|
|
||||||
|
class PersonalMcpMetadata(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="ignore", str_strip_whitespace=True)
|
||||||
|
|
||||||
|
id: str
|
||||||
|
version: str
|
||||||
|
tags: list[str] = Field(default_factory=list)
|
||||||
|
capabilities: list[str] = Field(min_length=1)
|
||||||
|
depends_on: list[str] = Field(default_factory=list)
|
||||||
|
references: dict[str, ReferenceEntry] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
@field_validator("id")
|
||||||
|
@classmethod
|
||||||
|
def validate_id(cls, value: str) -> str:
|
||||||
|
if not SKILL_ID_RE.fullmatch(value):
|
||||||
|
raise ValueError("id must be lowercase kebab-case and start with a letter")
|
||||||
|
return value
|
||||||
|
|
||||||
|
@field_validator("version")
|
||||||
|
@classmethod
|
||||||
|
def validate_version(cls, value: str) -> str:
|
||||||
|
if not SEMVER_RE.fullmatch(value):
|
||||||
|
raise ValueError("version must be semver")
|
||||||
|
return value
|
||||||
|
|
||||||
|
@field_validator("depends_on")
|
||||||
|
@classmethod
|
||||||
|
def validate_depends_on(cls, value: list[str]) -> list[str]:
|
||||||
|
for dep in value:
|
||||||
|
if not SKILL_ID_RE.fullmatch(dep):
|
||||||
|
raise ValueError(f"invalid depends_on skill id: {dep}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
@field_validator("references")
|
||||||
|
@classmethod
|
||||||
|
def validate_reference_ids(cls, value: dict[str, ReferenceEntry]) -> dict[str, ReferenceEntry]:
|
||||||
|
for ref_id in value:
|
||||||
|
if not SKILL_ID_RE.fullmatch(ref_id):
|
||||||
|
raise ValueError(f"invalid reference id: {ref_id}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def ensure_primary_capability(self) -> "PersonalMcpMetadata":
|
||||||
|
expected = f"resource://skills/{self.id}/document"
|
||||||
|
if expected not in self.capabilities:
|
||||||
|
raise ValueError(f"capabilities must include {expected}")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class SkillFrontmatter(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="ignore", str_strip_whitespace=True)
|
||||||
|
|
||||||
|
# Anthropic/Agent Skills fields
|
||||||
|
name: str = Field(min_length=1, max_length=64)
|
||||||
|
description: str = Field(min_length=1, max_length=1024)
|
||||||
|
when_to_use: str | None = None
|
||||||
|
allowed_tools: str | list[str] | None = Field(default=None, alias="allowed-tools")
|
||||||
|
disallowed_tools: str | list[str] | None = Field(default=None, alias="disallowed-tools")
|
||||||
|
disable_model_invocation: bool | None = Field(default=None, alias="disable-model-invocation")
|
||||||
|
user_invocable: bool | None = Field(default=None, alias="user-invocable")
|
||||||
|
argument_hint: str | None = Field(default=None, alias="argument-hint")
|
||||||
|
arguments: str | list[str] | None = None
|
||||||
|
license: str | None = None
|
||||||
|
compatibility: str | None = None
|
||||||
|
metadata: dict[str, str] | None = None
|
||||||
|
|
||||||
|
# Repository extension block
|
||||||
|
x_personal_mcp: PersonalMcpMetadata = Field(alias="x-personal-mcp")
|
||||||
|
|
||||||
|
@field_validator("name")
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, value: str) -> str:
|
||||||
|
if not SKILL_ID_RE.fullmatch(value):
|
||||||
|
raise ValueError("name must be lowercase kebab-case and start with a letter")
|
||||||
|
if "anthropic" in value or "claude" in value:
|
||||||
|
raise ValueError("name must not contain reserved words anthropic or claude")
|
||||||
|
return value
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def cross_validate(self) -> "SkillFrontmatter":
|
||||||
|
if self.x_personal_mcp.id != self.name:
|
||||||
|
raise ValueError("x-personal-mcp.id must exactly match name")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
def validate_skill_frontmatter(raw: dict[str, Any], skill_dir_name: str) -> SkillFrontmatter:
|
||||||
|
model = SkillFrontmatter.model_validate(raw)
|
||||||
|
if model.name != skill_dir_name:
|
||||||
|
raise ValueError("frontmatter name must exactly match skill directory name")
|
||||||
|
return model
|
||||||
|
```
|
||||||
|
|
||||||
|
Validation behavior contract:
|
||||||
|
|
||||||
|
- Validate required core fields and relationships during registry load before FastMCP resource/tool registration.
|
||||||
|
- Allow unknown additive fields so frontmatter can evolve without blocking startup.
|
||||||
|
- Treat hard contract violations (missing required fields, invalid ids, broken required mappings) as startup errors.
|
||||||
|
- Treat non-critical compatibility issues as warnings when possible.
|
||||||
|
- Error messages should include skill path and failing field for CI readability.
|
||||||
|
|
||||||
|
Projection mode contract (for Anthropic API upload pipelines):
|
||||||
|
|
||||||
|
- Parse with `SkillFrontmatter` first.
|
||||||
|
- Emit Anthropic-safe frontmatter with standard fields only.
|
||||||
|
- Serialize repository metadata into standard `metadata` as namespaced keys.
|
||||||
|
- Preserve the canonical authored source in `x-personal-mcp`; projection output is a build artifact.
|
||||||
|
|
||||||
|
### Anthropic Upload Compatibility Rule
|
||||||
|
|
||||||
|
- Anthropic documentation guarantees behavior for standard frontmatter fields but does not explicitly guarantee handling of arbitrary unknown top-level keys.
|
||||||
|
- Therefore, publishing pipelines that target strict API compatibility should support a projection mode that emits only standard frontmatter fields for upload.
|
||||||
|
- In projection mode, repository extension metadata is serialized into the standard `metadata` field (for example as namespaced keys or JSON-encoded values), while source-of-truth authoring remains in `x-personal-mcp`.
|
||||||
|
|
||||||
|
### FastMCP Native Metadata Surfaces (Research Baseline)
|
||||||
|
|
||||||
|
Resources (`@mcp.resource` and templates) support native definition metadata:
|
||||||
|
|
||||||
|
- `name`, `description`, `mime_type`, `tags`
|
||||||
|
- `annotations` (`readOnlyHint`, `idempotentHint`)
|
||||||
|
- `icons`
|
||||||
|
- `meta` (custom metadata passed through to the MCP client resource object)
|
||||||
|
- `version`
|
||||||
|
- `enabled` (deprecated in v3; prefer server-level `mcp.enable()` / `mcp.disable()`)
|
||||||
|
|
||||||
|
Resources support runtime metadata:
|
||||||
|
|
||||||
|
- `ResourceContent.meta` (item-level)
|
||||||
|
- `ResourceResult.meta` (result-level `_meta`)
|
||||||
|
|
||||||
|
Tools (`@mcp.tool`) support native definition metadata:
|
||||||
|
|
||||||
|
- `name`, `description`, `tags`
|
||||||
|
- `annotations` (`title`, `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`)
|
||||||
|
- `icons`
|
||||||
|
- `meta` (custom metadata passed through to the MCP client tool object)
|
||||||
|
- `version`
|
||||||
|
- `timeout`, `output_schema`, `run_in_thread`
|
||||||
|
- `enabled` (deprecated in v3; prefer server-level `mcp.enable()` / `mcp.disable()`)
|
||||||
|
|
||||||
|
Tools support runtime metadata:
|
||||||
|
|
||||||
|
- `ToolResult.meta` (execution-level metadata for each call)
|
||||||
|
|
||||||
|
### Frontmatter To FastMCP Mapping Contract
|
||||||
|
|
||||||
|
At server startup, map `x-personal-mcp` fields into FastMCP registration as follows:
|
||||||
|
|
||||||
|
- `x-personal-mcp.id` -> canonical URI namespace and identity checks.
|
||||||
|
- `description` -> default `description` for the primary skill document resource.
|
||||||
|
- `x-personal-mcp.tags` -> `tags` on resources/tools.
|
||||||
|
- `x-personal-mcp.version` -> `version` on resources/tools.
|
||||||
|
- `x-personal-mcp.capabilities` -> registered URI list plus catalog exposure.
|
||||||
|
- `x-personal-mcp.references[*]` -> resource templates or concrete resources with:
|
||||||
|
- `mime_type` from reference entry (or default)
|
||||||
|
- `meta` including `skill_id`, `ref_id`, and source `path`
|
||||||
|
- read-only annotations for documentation resources
|
||||||
|
- `x-personal-mcp.depends_on` -> catalog dependency graph metadata and validation checks.
|
||||||
|
|
||||||
|
### Invariants This Contract Guarantees
|
||||||
|
|
||||||
|
- Anthropic-required frontmatter stays valid for custom skill upload and Claude Code loading.
|
||||||
|
- MCP-specific metadata remains embedded in SKILL.md frontmatter, with no `metadata.yaml` sidecar.
|
||||||
|
- FastMCP registration uses only native metadata fields for resources/tools.
|
||||||
|
- Reference ids and metadata can evolve with low-friction updates while internal file layout under `references/` stays refactor-friendly.
|
||||||
|
|
||||||
|
### Non-goals For Step 2
|
||||||
|
|
||||||
|
- No URI versioning/deprecation rollout policy details (handled in Step 3).
|
||||||
|
- No migration script design from existing `metadata.yaml` files.
|
||||||
|
- No runtime caching/indexing performance tuning details.
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
**Step 3 Results: URI Contract and Compatibility Policy**
|
||||||
|
|
||||||
|
This section finalizes Step 3 by defining the canonical resource URI contract, template parameter rules, and explicit compatibility/versioning policy for URIs and reference ids.
|
||||||
|
|
||||||
|
### Step Deliverable
|
||||||
|
|
||||||
|
- Update the current `docs/` directory with the finalized Step 3 URI contract and compatibility policy content from this document.
|
||||||
|
|
||||||
|
### Canonical URI Surface (Normative)
|
||||||
|
|
||||||
|
The public, preferred URIs are:
|
||||||
|
|
||||||
|
1. `resource://catalog/skills_index`
|
||||||
|
2. `resource://catalog/skills/{skill_id}`
|
||||||
|
3. `resource://skills/{skill_id}/document`
|
||||||
|
4. `resource://skills/{skill_id}/references/{ref_id}`
|
||||||
|
5. `resource://docs/{path*}`
|
||||||
|
|
||||||
|
Contract intent:
|
||||||
|
|
||||||
|
- Catalog URIs are discovery surfaces.
|
||||||
|
- Skill URIs are primary per-skill guidance surfaces.
|
||||||
|
- Docs wildcard URI is a direct authored-markdown access surface under `docs/`.
|
||||||
|
|
||||||
|
### URI Semantics
|
||||||
|
|
||||||
|
`resource://catalog/skills_index`
|
||||||
|
|
||||||
|
- Returns a compact list of skill records for discovery.
|
||||||
|
- One entry per `skill_id`.
|
||||||
|
- Must include enough metadata for client-side selection (at minimum id, name, description, tags, capabilities).
|
||||||
|
|
||||||
|
`resource://catalog/skills/{skill_id}`
|
||||||
|
|
||||||
|
- Returns one normalized record for `skill_id`.
|
||||||
|
- Must include canonical document URI and declared reference ids.
|
||||||
|
- Returns not-found when `skill_id` does not exist.
|
||||||
|
|
||||||
|
`resource://skills/{skill_id}/document`
|
||||||
|
|
||||||
|
- Returns the canonical `SKILL.md` authored content for that skill.
|
||||||
|
- `skill_id` must match Step 1 stable id rules.
|
||||||
|
|
||||||
|
`resource://skills/{skill_id}/references/{ref_id}`
|
||||||
|
|
||||||
|
- Returns one reference document declared in the skill frontmatter references manifest.
|
||||||
|
- `ref_id` is the stable public handle for that reference document.
|
||||||
|
|
||||||
|
`resource://docs/{path*}`
|
||||||
|
|
||||||
|
- Returns authored markdown at a normalized relative path under `docs/`.
|
||||||
|
- Supports nested paths via RFC6570 wildcard expansion.
|
||||||
|
- Typical examples: `index.md`, `usage.md`, `skills/<skill-id>/SKILL.md`, `skills/<skill-id>/references/<file>.md`.
|
||||||
|
|
||||||
|
### Template Parameter and Validation Rules
|
||||||
|
|
||||||
|
`skill_id`
|
||||||
|
|
||||||
|
- Lowercase kebab-case.
|
||||||
|
- Must satisfy Step 1 stable id rules.
|
||||||
|
|
||||||
|
`ref_id`
|
||||||
|
|
||||||
|
- Lowercase kebab-case.
|
||||||
|
- Must be declared in the skill’s references manifest.
|
||||||
|
|
||||||
|
`path*`
|
||||||
|
|
||||||
|
- Relative POSIX path only.
|
||||||
|
- No leading slash.
|
||||||
|
- No `..` traversal segments.
|
||||||
|
- Resolves only inside `docs/`.
|
||||||
|
- This surface is markdown-only in end state (`.md` files).
|
||||||
|
|
||||||
|
### URI Versioning Policy
|
||||||
|
|
||||||
|
Default rule:
|
||||||
|
|
||||||
|
- Keep URIs unversioned by default.
|
||||||
|
- Allow URI and payload updates when they improve clarity or implementation simplicity.
|
||||||
|
|
||||||
|
Breaking-change rule:
|
||||||
|
|
||||||
|
- Breaking changes use direct replacement of the canonical URI family.
|
||||||
|
- No compatibility aliases or dual URI families are maintained in this greenfield phase.
|
||||||
|
|
||||||
|
FastMCP version metadata usage:
|
||||||
|
|
||||||
|
- Resource `version` metadata MAY be used for implementation/version discovery.
|
||||||
|
- URI readability and maintainability remain the primary contract.
|
||||||
|
|
||||||
|
### Reference ID Compatibility Policy
|
||||||
|
|
||||||
|
`ref_id` is the public identifier for a reference document, separate from file path.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- Prefer keeping `ref_id` stable when practical.
|
||||||
|
- File paths may change without URI churn as long as the mapped `ref_id` resolves.
|
||||||
|
- If a reference is renamed, introduce a new `ref_id` and treat the old one as retired.
|
||||||
|
- Avoid reusing retired `ref_id` values for unrelated content.
|
||||||
|
|
||||||
|
### Invariants This Contract Guarantees
|
||||||
|
|
||||||
|
- One canonical URI pattern per core capability surface.
|
||||||
|
- Fast, low-friction URI evolution through direct replacement of canonical URIs.
|
||||||
|
- A single canonical catalog URI family with no alias maintenance overhead.
|
||||||
|
- Reference mappings can evolve with minimal churn.
|
||||||
|
|
||||||
|
### Non-goals For Step 3
|
||||||
|
|
||||||
|
- No implementation-specific transform wiring details (`VersionFilter`, mounts, provider composition).
|
||||||
|
- No migration script mechanics for auto-generating aliases.
|
||||||
|
- No authorization policy design for URI-level access control.
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
**Step 4 Results: Docs Registry Loader Design (importlib.resources + Fail-Fast Validation)**
|
||||||
|
|
||||||
|
This section finalizes Step 4 by defining a production-ready docs registry loader that reads packaged docs through Python resource APIs, parses SKILL.md frontmatter, validates schema and cross-links, and builds an immutable in-memory registry keyed by skill_id.
|
||||||
|
|
||||||
|
### Greenfield Framing (Normative)
|
||||||
|
|
||||||
|
This Step 4 design is for the greenfield target state:
|
||||||
|
|
||||||
|
1. No legacy metadata sidecars (`metadata.yaml`) are part of the runtime contract.
|
||||||
|
2. No dual-loader compatibility path is required.
|
||||||
|
3. Registry loading from packaged resources is the only runtime source of truth.
|
||||||
|
4. Compatibility shims are prohibited.
|
||||||
|
|
||||||
|
### Research Baseline (Python + Design Guidance)
|
||||||
|
|
||||||
|
Authoritative references used for this step:
|
||||||
|
|
||||||
|
1. Python `importlib.resources` docs (`files`, `as_file`, `Traversable` APIs)
|
||||||
|
2. Python `importlib.resources.abc` docs (`Traversable`, path traversal semantics, joinpath compatibility notes)
|
||||||
|
3. Pydantic v2 model/validation docs (`model_validate`, `ValidationError`, strictness and extra handling)
|
||||||
|
4. Python packaging guidance for including package data in wheels/sdists
|
||||||
|
|
||||||
|
Best-practice conclusions applied to this design:
|
||||||
|
|
||||||
|
1. Prefer `importlib.resources.files(<package>).joinpath(...)` over filesystem assumptions so stdio deployments from installed wheels work.
|
||||||
|
2. Treat resources as potentially non-filesystem artifacts (zip-import compatible); only use `as_file(...)` when an actual OS path is required.
|
||||||
|
3. Validate metadata with explicit Pydantic models and fail startup on contract violations.
|
||||||
|
4. Keep registry load deterministic (sorted traversal, stable error messages, no hidden fallback mutations).
|
||||||
|
5. Resolve references via manifest ids declared in frontmatter, not by global file conventions.
|
||||||
|
|
||||||
|
### Loader Responsibilities (Normative)
|
||||||
|
|
||||||
|
The Step 4 loader MUST:
|
||||||
|
|
||||||
|
1. Read canonical docs from package resources (not repo-root paths).
|
||||||
|
2. Discover all skill directories under `docs/skills/` in packaged resources.
|
||||||
|
3. For each skill, read and parse `SKILL.md` frontmatter.
|
||||||
|
4. Validate frontmatter using the Step 2 schema contract.
|
||||||
|
5. Validate directory/id invariants from Step 1 (directory name equals frontmatter id).
|
||||||
|
6. Validate URI/reference semantics from Step 3 assumptions.
|
||||||
|
7. Build a single in-memory registry keyed by `skill_id`.
|
||||||
|
8. Fail fast on any integrity error before FastMCP resource registration.
|
||||||
|
9. Precompute compact discovery projections so index resources can be served without reading full markdown bodies at request time.
|
||||||
|
|
||||||
|
### Package Resource Contract
|
||||||
|
|
||||||
|
Runtime anchor:
|
||||||
|
|
||||||
|
1. The loader resolves content from an importable package anchor, for example `personal_mcp`.
|
||||||
|
2. Docs root is located as `files(anchor).joinpath("docs")` when docs are packaged at package root, or an equivalent configured subpath.
|
||||||
|
3. Skill root is `docs/skills`.
|
||||||
|
|
||||||
|
Resource assumptions:
|
||||||
|
|
||||||
|
1. `SKILL.md` is UTF-8 text.
|
||||||
|
2. Reference files declared in frontmatter are UTF-8 markdown by default unless otherwise declared.
|
||||||
|
3. Path resolution always remains inside the same skill directory.
|
||||||
|
|
||||||
|
### Registry Data Model
|
||||||
|
|
||||||
|
Build immutable runtime records with explicit structure:
|
||||||
|
|
||||||
|
1. `SkillRecord`
|
||||||
|
- `skill_id`
|
||||||
|
- `name`
|
||||||
|
- `description`
|
||||||
|
- `version`
|
||||||
|
- `tags`
|
||||||
|
- `capabilities`
|
||||||
|
- `depends_on`
|
||||||
|
- `document_uri`
|
||||||
|
- `document_relpath` (canonical resource-relative path)
|
||||||
|
- `references` map keyed by `ref_id`
|
||||||
|
2. `ReferenceRecord`
|
||||||
|
- `ref_id`
|
||||||
|
- `uri`
|
||||||
|
- `relpath`
|
||||||
|
- `mime_type`
|
||||||
|
- `title`
|
||||||
|
3. `DocsRegistry`
|
||||||
|
- `skills_by_id: dict[str, SkillRecord]`
|
||||||
|
- `skills_in_load_order: list[str]` (deterministic ordering)
|
||||||
|
- helper indexes for catalog payload generation
|
||||||
|
- `skills_summary_in_load_order: list[SkillSummaryRecord]` for progressive discovery responses
|
||||||
|
- filter indexes (for example by tag/capability) derived once at startup
|
||||||
|
|
||||||
|
4. `SkillSummaryRecord`
|
||||||
|
- `skill_id`
|
||||||
|
- `name`
|
||||||
|
- `description`
|
||||||
|
- `tags`
|
||||||
|
- `capabilities`
|
||||||
|
- `document_uri`
|
||||||
|
- optional `version`
|
||||||
|
|
||||||
|
Immutability rule:
|
||||||
|
|
||||||
|
1. Once built, registry records are treated as read-only for the process lifetime.
|
||||||
|
2. No runtime mutation during requests; refresh only via process restart.
|
||||||
|
|
||||||
|
### Frontmatter Parsing Contract
|
||||||
|
|
||||||
|
`SKILL.md` parse steps:
|
||||||
|
|
||||||
|
1. Read full markdown text from resource.
|
||||||
|
2. Parse YAML frontmatter block at file start (between the first two `---` delimiters).
|
||||||
|
3. Parse YAML with safe loader semantics.
|
||||||
|
4. Validate parsed object with Step 2 Pydantic model(s).
|
||||||
|
5. Preserve markdown body as document content payload.
|
||||||
|
|
||||||
|
Parsing failure behavior:
|
||||||
|
|
||||||
|
1. Missing frontmatter block: startup error.
|
||||||
|
2. Invalid YAML: startup error with skill path and YAML parser detail.
|
||||||
|
3. Missing required fields (`name`, `description`, `x-personal-mcp` contract fields): startup error.
|
||||||
|
|
||||||
|
### Validation Pipeline (Fail-Fast)
|
||||||
|
|
||||||
|
Validation happens in this order:
|
||||||
|
|
||||||
|
1. Structural discovery validation
|
||||||
|
- skill directory exists under `docs/skills`
|
||||||
|
- required `SKILL.md` exists for each discovered skill
|
||||||
|
2. Schema validation
|
||||||
|
- Pydantic frontmatter validation for all required and constrained fields
|
||||||
|
3. Identity validation
|
||||||
|
- frontmatter `name` equals `x-personal-mcp.id`
|
||||||
|
- frontmatter id equals skill directory name
|
||||||
|
4. Reference manifest validation
|
||||||
|
- unique `ref_id` keys per skill
|
||||||
|
- each manifest path is relative, in-skill, and under `references/`
|
||||||
|
- each manifest target exists and is a file
|
||||||
|
5. Dependency graph validation
|
||||||
|
- every `depends_on` target exists in discovered skill set
|
||||||
|
- no self-dependency
|
||||||
|
- cycle detection enabled (hard error on cycle)
|
||||||
|
6. Capability sanity checks
|
||||||
|
- required primary capability `resource://skills/{skill_id}/document` is present
|
||||||
|
7. Global uniqueness checks
|
||||||
|
- no duplicate `skill_id`
|
||||||
|
- no duplicate canonical resource URIs generated from registry
|
||||||
|
8. Discovery payload checks
|
||||||
|
- summary fields required by catalog index are present and non-empty
|
||||||
|
- summary generation does not require reading markdown body content during request handling
|
||||||
|
|
||||||
|
### Error Model and Reporting
|
||||||
|
|
||||||
|
Error handling contract:
|
||||||
|
|
||||||
|
1. Collect errors per validation phase for clarity, then raise one startup exception containing all findings.
|
||||||
|
2. Error messages must include:
|
||||||
|
- skill id (when known)
|
||||||
|
- packaged relative path
|
||||||
|
- violated rule
|
||||||
|
- actionable fix hint
|
||||||
|
3. If any error exists, registry is not published and FastMCP resource registration does not proceed.
|
||||||
|
|
||||||
|
Recommended exception shape:
|
||||||
|
|
||||||
|
1. `DocsRegistryValidationError(errors: list[RegistryIssue])`
|
||||||
|
2. `RegistryIssue` fields: `code`, `message`, `skill_id`, `path`, `hint`
|
||||||
|
|
||||||
|
### Determinism and Runtime Safety
|
||||||
|
|
||||||
|
Determinism rules:
|
||||||
|
|
||||||
|
1. Traverse directories in sorted order.
|
||||||
|
2. Normalize all stored relative paths to POSIX form.
|
||||||
|
3. Normalize ids/tags exactly once at parse boundary.
|
||||||
|
4. Produce stable catalog ordering to reduce client churn.
|
||||||
|
5. Produce stable summary projections and filter indexes from the same normalized source records.
|
||||||
|
|
||||||
|
Runtime safety rules:
|
||||||
|
|
||||||
|
1. No dependence on `Path(__file__)` or repository root.
|
||||||
|
2. No ad-hoc fallback probing across multiple locations.
|
||||||
|
3. No lazy validation deferred until first request.
|
||||||
|
|
||||||
|
### Integration Plan for Existing Modules
|
||||||
|
|
||||||
|
Primary integration target:
|
||||||
|
|
||||||
|
1. Implement the canonical package-resource-based registry loader in `src/personal_mcp/skills/document_loader.py` as the only supported runtime loader path.
|
||||||
|
|
||||||
|
Catalog integration:
|
||||||
|
|
||||||
|
1. Update `src/personal_mcp/catalog/server.py` to consume the shared in-memory registry as the only catalog data source.
|
||||||
|
2. Keep catalog payload normalization deterministic and sourced from registry records only.
|
||||||
|
|
||||||
|
Startup wiring:
|
||||||
|
|
||||||
|
1. Initialize registry once during app/server startup in `src/personal_mcp/main.py` or equivalent composition point.
|
||||||
|
2. Pass registry to resource registration step (Step 5).
|
||||||
|
|
||||||
|
### Proposed Loader API Surface
|
||||||
|
|
||||||
|
Use a small, testable API:
|
||||||
|
|
||||||
|
1. `load_docs_registry(*, package_anchor: str, docs_root: str = "docs") -> DocsRegistry`
|
||||||
|
2. `read_skill_document(registry: DocsRegistry, skill_id: str) -> DocumentPayload`
|
||||||
|
3. `read_skill_reference(registry: DocsRegistry, skill_id: str, ref_id: str) -> DocumentPayload`
|
||||||
|
|
||||||
|
Design constraints:
|
||||||
|
|
||||||
|
1. Loader functions are pure relative to package resources and input args.
|
||||||
|
2. No global mutable singleton required for unit tests.
|
||||||
|
3. Caching is explicit and owned by startup composition.
|
||||||
|
|
||||||
|
### Test and Validation Plan (Step 4 Scope)
|
||||||
|
|
||||||
|
Unit tests:
|
||||||
|
|
||||||
|
1. valid multi-skill registry load from packaged test fixtures
|
||||||
|
2. duplicate id detection
|
||||||
|
3. missing SKILL.md detection
|
||||||
|
4. invalid frontmatter field constraints
|
||||||
|
5. broken reference target detection
|
||||||
|
6. invalid depends_on target detection
|
||||||
|
7. cycle detection in depends_on graph
|
||||||
|
8. deterministic output ordering across runs
|
||||||
|
|
||||||
|
Packaging/runtime tests:
|
||||||
|
|
||||||
|
1. install built wheel in isolated env
|
||||||
|
2. load registry via `importlib.resources.files(...)`
|
||||||
|
3. assert representative skill document/reference are readable
|
||||||
|
|
||||||
|
Expected command path in this repo:
|
||||||
|
|
||||||
|
1. `uv run pytest -q`
|
||||||
|
|
||||||
|
### Acceptance Criteria for Step 4 Completion
|
||||||
|
|
||||||
|
Step 4 is complete when all are true:
|
||||||
|
|
||||||
|
1. Registry loads exclusively from packaged resources.
|
||||||
|
2. All Step 2 and Step 3 dependent validations are enforced at startup.
|
||||||
|
3. Invalid docs state blocks startup with actionable diagnostics.
|
||||||
|
4. Registry is deterministic and immutable for runtime use.
|
||||||
|
5. Catalog and later resource registration can consume registry without direct filesystem scanning.
|
||||||
|
|
||||||
|
### Non-goals for Step 4
|
||||||
|
|
||||||
|
1. No FastMCP resource registration wiring details (Step 5).
|
||||||
|
2. No discovery-tool fallback behavior design (Step 6).
|
||||||
|
3. No final packaging/build-system migration mechanics (Step 7).
|
||||||
|
4. No backward-compat alias rollout mechanics in the greenfield baseline.
|
||||||
|
5. No compatibility layer of any kind (URI aliases, dual reads, adapter shims, or legacy schema bridges).
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
**Step 5 Results: Registry-Driven FastMCP Resource Registration (RFC6570 + Startup Safety)**
|
||||||
|
|
||||||
|
This section finalizes Step 5 by defining how FastMCP resources are registered from the Step 4 docs registry using RFC6570 URI templates, explicit metadata, and strict duplicate-registration safety.
|
||||||
|
|
||||||
|
### Greenfield Framing (Normative)
|
||||||
|
|
||||||
|
This Step 5 design is for the greenfield target state:
|
||||||
|
|
||||||
|
1. Registry-driven resources are the primary and authoritative discovery/read surface.
|
||||||
|
2. No legacy per-skill hardcoded resource registration is retained.
|
||||||
|
3. Resource contracts are defined for net-new clients and replace prior contracts without transition shims.
|
||||||
|
4. Step 6 tool fallback layers on top of this resource contract, not as a competing source of truth.
|
||||||
|
5. Breaking changes are intentional in this full-refactor phase.
|
||||||
|
|
||||||
|
### Research Baseline (FastMCP + URI Templates)
|
||||||
|
|
||||||
|
Authoritative references used for this step:
|
||||||
|
|
||||||
|
1. FastMCP Resources and Templates docs (resource decorator, template behavior)
|
||||||
|
2. FastMCP RFC6570 support docs (simple params, wildcard params, query params)
|
||||||
|
3. FastMCP duplicate handling docs (`on_duplicate_resources`)
|
||||||
|
4. FastMCP annotations guidance (`readOnlyHint`, `idempotentHint`)
|
||||||
|
|
||||||
|
Best-practice conclusions applied to this design:
|
||||||
|
|
||||||
|
1. Use URI templates for parameterized resources instead of generating N static resource handlers.
|
||||||
|
2. Use wildcard template parameters (`{path*}`) for hierarchical docs paths.
|
||||||
|
3. Set startup duplicate policy to `on_duplicate_resources="error"` to fail fast on contract collisions.
|
||||||
|
4. Set explicit `mime_type` and resource annotations for all docs resources.
|
||||||
|
5. Keep registration deterministic and sourced only from the validated Step 4 registry.
|
||||||
|
|
||||||
|
### Registration Responsibilities (Normative)
|
||||||
|
|
||||||
|
The Step 5 registration layer MUST:
|
||||||
|
|
||||||
|
1. Consume only the validated in-memory registry produced by Step 4.
|
||||||
|
2. Register canonical resource discovery surfaces and skill document/reference surfaces.
|
||||||
|
3. Use RFC6570 templates where URI patterns are parameterized.
|
||||||
|
4. Use wildcard templates where path depth is variable.
|
||||||
|
5. Attach read-only/idempotent annotations to documentation resources.
|
||||||
|
6. Set explicit MIME types for all registered resources.
|
||||||
|
7. Fail startup if duplicate URI/template keys are encountered.
|
||||||
|
|
||||||
|
### Canonical Resource Surface (from Registry)
|
||||||
|
|
||||||
|
The preferred resources registered in this phase are:
|
||||||
|
|
||||||
|
1. `resource://catalog/skills_index`
|
||||||
|
2. `resource://catalog/skills_index{?q,tag,capability,cursor,limit}` (optional filtered/paginated discovery template)
|
||||||
|
3. `resource://catalog/skills/{skill_id}`
|
||||||
|
4. `resource://skills/{skill_id}/document`
|
||||||
|
5. `resource://skills/{skill_id}/references/{ref_id}`
|
||||||
|
6. `resource://docs/{path*}`
|
||||||
|
|
||||||
|
Registration decision rules:
|
||||||
|
|
||||||
|
1. Use static resource registration for fixed singleton endpoints (for example `skills_index`).
|
||||||
|
2. Use template registration for parameterized endpoints (`{skill_id}`, `{ref_id}`) and optional discovery query templates.
|
||||||
|
3. Use wildcard template registration for hierarchical docs routing (`{path*}`).
|
||||||
|
4. Keep the singleton and query-template discovery surfaces semantically equivalent (same schema, query template adds filtering/pagination only).
|
||||||
|
|
||||||
|
### Progressive Discovery Contract
|
||||||
|
|
||||||
|
Discovery-first behavior for Step 5 resources:
|
||||||
|
|
||||||
|
1. `skills_index` returns summaries only (no embedded full SKILL.md bodies).
|
||||||
|
2. Each summary includes canonical follow-up URIs so clients can progressively fetch detail (`catalog/skills/{skill_id}` then `skills/{skill_id}/document`).
|
||||||
|
3. Filtered/paginated discovery uses RFC6570 query params (`q`, `tag`, `capability`, `cursor`, `limit`) with deterministic ordering.
|
||||||
|
4. Handlers should enforce bounded page size and return explicit continuation metadata when pagination is active.
|
||||||
|
5. Errors for unsupported filter params or invalid cursor/limit are explicit and actionable.
|
||||||
|
|
||||||
|
### RFC6570 Template Contract
|
||||||
|
|
||||||
|
Path parameters:
|
||||||
|
|
||||||
|
1. `{skill_id}` and `{ref_id}` are single-segment template params.
|
||||||
|
2. `{path*}` is a wildcard param and may capture multi-segment paths separated by `/`.
|
||||||
|
|
||||||
|
Validation contract at resource-read time:
|
||||||
|
|
||||||
|
1. `skill_id` must exist in registry.
|
||||||
|
2. `ref_id` must exist in that skill’s reference manifest.
|
||||||
|
3. wildcard `path*` must normalize to an allowed docs-relative markdown path.
|
||||||
|
4. invalid params return explicit not-found or validation errors (no silent fallback).
|
||||||
|
|
||||||
|
Template function signature contract:
|
||||||
|
|
||||||
|
1. Required URI params must exist as function parameters.
|
||||||
|
2. Avoid hidden implicit params not represented in template.
|
||||||
|
3. Keep template handlers side-effect free.
|
||||||
|
|
||||||
|
### Metadata and Annotation Contract
|
||||||
|
|
||||||
|
Each docs/resource registration should specify explicit metadata:
|
||||||
|
|
||||||
|
1. `mime_type`
|
||||||
|
- skill docs and references: `text/markdown`
|
||||||
|
- catalog payloads: `application/json`
|
||||||
|
2. `annotations`
|
||||||
|
- `readOnlyHint: true`
|
||||||
|
- `idempotentHint: true`
|
||||||
|
3. `tags`
|
||||||
|
- include stable categories such as `catalog`, `skill-doc`, `reference`, `docs`
|
||||||
|
4. `version`
|
||||||
|
- project-defined version from registry metadata where applicable
|
||||||
|
5. `meta`
|
||||||
|
- include normalized identifiers (for example `skill_id`, `ref_id`, `source_relpath`) when useful
|
||||||
|
|
||||||
|
### Startup Safety and Duplicate Policy
|
||||||
|
|
||||||
|
FastMCP initialization contract for this phase:
|
||||||
|
|
||||||
|
1. Construct the root server with `on_duplicate_resources="error"`.
|
||||||
|
2. Register all Step 5 resources during startup composition before serving traffic.
|
||||||
|
3. Treat duplicate registration as a hard startup failure.
|
||||||
|
|
||||||
|
Duplicate conflict classes covered:
|
||||||
|
|
||||||
|
1. static URI vs static URI collision
|
||||||
|
2. static URI vs template key collision
|
||||||
|
3. template URI vs template URI collision
|
||||||
|
4. conflicting registrations introduced by future aliases without explicit migration handling
|
||||||
|
|
||||||
|
### Registration Architecture
|
||||||
|
|
||||||
|
Use one dedicated registration module that converts registry records into FastMCP resources.
|
||||||
|
|
||||||
|
Recommended API:
|
||||||
|
|
||||||
|
1. `register_docs_resources(mcp: FastMCP, registry: DocsRegistry) -> None`
|
||||||
|
|
||||||
|
Responsibilities of `register_docs_resources`:
|
||||||
|
|
||||||
|
1. register singleton catalog resources
|
||||||
|
2. register parameterized catalog/detail templates
|
||||||
|
3. register skill document and reference templates
|
||||||
|
4. register docs wildcard template
|
||||||
|
5. apply shared annotations and MIME defaults consistently
|
||||||
|
|
||||||
|
Separation of concerns:
|
||||||
|
|
||||||
|
1. Step 4 validates and normalizes docs state.
|
||||||
|
2. Step 5 only registers handlers and reads from validated registry state.
|
||||||
|
3. Request handlers do not re-discover filesystem/package structure.
|
||||||
|
|
||||||
|
### Handler Behavior Contract
|
||||||
|
|
||||||
|
Catalog handlers:
|
||||||
|
|
||||||
|
1. `skills_index` returns compact deterministic discovery payload (summary records only) and supports progressive follow-up links.
|
||||||
|
2. `skills/{skill_id}` returns one normalized detail record or not-found.
|
||||||
|
|
||||||
|
Skill document handlers:
|
||||||
|
|
||||||
|
1. `skills/{skill_id}/document` returns canonical SKILL markdown content.
|
||||||
|
2. MIME type is always `text/markdown`.
|
||||||
|
|
||||||
|
Reference handlers:
|
||||||
|
|
||||||
|
1. `skills/{skill_id}/references/{ref_id}` resolves via frontmatter manifest mapping.
|
||||||
|
2. MIME type is explicit from manifest or defaults to `text/markdown`.
|
||||||
|
|
||||||
|
Wildcard docs handler:
|
||||||
|
|
||||||
|
1. `docs/{path*}` serves markdown docs under canonical packaged docs tree.
|
||||||
|
2. traversal outside docs root is blocked.
|
||||||
|
|
||||||
|
### Integration Plan for Existing Modules
|
||||||
|
|
||||||
|
Primary composition updates:
|
||||||
|
|
||||||
|
1. Implement registry-driven registration in [src/personal_mcp/mcp.py](src/personal_mcp/mcp.py) as the canonical resource composition path.
|
||||||
|
2. Keep [src/personal_mcp/main.py](src/personal_mcp/main.py) responsible for startup wiring order (load registry first, then register resources).
|
||||||
|
3. Use [src/personal_mcp/catalog/server.py](src/personal_mcp/catalog/server.py) as registry-backed handlers only.
|
||||||
|
|
||||||
|
Lifecycle order (required):
|
||||||
|
|
||||||
|
1. load and validate registry (Step 4)
|
||||||
|
2. initialize FastMCP with duplicate error policy
|
||||||
|
3. register all Step 5 resources/templates
|
||||||
|
4. start server
|
||||||
|
|
||||||
|
### Testing Plan (Step 5 Scope)
|
||||||
|
|
||||||
|
Unit/integration tests:
|
||||||
|
|
||||||
|
1. resource registration succeeds with valid registry
|
||||||
|
2. duplicate resource registration fails at startup
|
||||||
|
3. `skills/{skill_id}` template resolves expected record
|
||||||
|
4. `skills/{skill_id}/document` returns markdown with correct MIME
|
||||||
|
5. `skills/{skill_id}/references/{ref_id}` resolves manifest-mapped file
|
||||||
|
6. `docs/{path*}` resolves nested docs paths and blocks traversal attempts
|
||||||
|
7. all registered docs resources include `readOnlyHint` and `idempotentHint`
|
||||||
|
8. catalog payload order is deterministic
|
||||||
|
9. filtered/paginated `skills_index{?q,tag,capability,cursor,limit}` responses are deterministic and schema-compatible with the singleton index response
|
||||||
|
10. catalog index payload excludes full markdown bodies and includes follow-up URIs for progressive reads
|
||||||
|
|
||||||
|
Smoke tests:
|
||||||
|
|
||||||
|
1. list resources includes singleton and template entries
|
||||||
|
2. read representative skill doc URI and reference URI successfully
|
||||||
|
3. read representative wildcard docs URI successfully
|
||||||
|
|
||||||
|
### Acceptance Criteria for Step 5 Completion
|
||||||
|
|
||||||
|
Step 5 is complete when all are true:
|
||||||
|
|
||||||
|
1. Resource registration is fully registry-driven (no per-skill hardcoded decorators required for core docs surfaces).
|
||||||
|
2. RFC6570 templates are used for parameterized URI families, including wildcard where needed.
|
||||||
|
3. All docs resources declare explicit MIME types and read-only/idempotent annotations.
|
||||||
|
4. `on_duplicate_resources="error"` is enabled and verified by tests.
|
||||||
|
5. Startup fails safely on registration conflicts.
|
||||||
|
|
||||||
|
### Non-goals for Step 5
|
||||||
|
|
||||||
|
1. No tool fallback discovery behavior implementation (Step 6).
|
||||||
|
2. No packaging build inclusion mechanics (Step 7).
|
||||||
|
3. No CI gate expansion details (Step 9).
|
||||||
|
4. No migration shims for legacy URI aliases in the greenfield baseline.
|
||||||
|
5. No ranking-strategy implementation for discovery tools beyond what is needed to preserve deterministic resource-first discovery contracts.
|
||||||
|
6. No backward-compat resource aliases, adapter handlers, or dual registration paths.
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
**Step 6 Results: Resource-First Discovery and Tool Fallback Contract**
|
||||||
|
|
||||||
|
This section finalizes Step 6 by defining discovery behavior for clients that can attach MCP resources and the fallback behavior for clients or chat surfaces that must rely on MCP tools.
|
||||||
|
|
||||||
|
### Step Deliverable
|
||||||
|
|
||||||
|
- Update the current `docs/` directory with the finalized Step 6 discovery and fallback contract content from this document.
|
||||||
|
|
||||||
|
### Primary Source Baseline (Repository Docs)
|
||||||
|
|
||||||
|
Step 6 is based on the current project contracts in:
|
||||||
|
|
||||||
|
1. `docs/architecture.md` (resource-first architecture and catalog role)
|
||||||
|
2. `docs/usage.md` (operating flows, bounded loading, and fallback sequence)
|
||||||
|
3. `docs/copilot.md` (client capability lanes and practical fallback behavior)
|
||||||
|
4. `docs/mcp_layout.md` (shared content source and thin-tool fallback position)
|
||||||
|
5. `docs/securing.md` (read-only/public-docs security invariant)
|
||||||
|
|
||||||
|
Normative conclusions from those sources:
|
||||||
|
|
||||||
|
1. Discovery stays resource-first.
|
||||||
|
2. Tool fallback is allowed, thin, and read-only.
|
||||||
|
3. Resources and tools must resolve to the same canonical authored markdown.
|
||||||
|
4. Fallback behavior should keep context bounded and deterministic.
|
||||||
|
|
||||||
|
### FastMCP Source Baseline (Authoritative References)
|
||||||
|
|
||||||
|
Step 6 fallback behavior and compatibility-layer expectations align with:
|
||||||
|
|
||||||
|
1. [FastMCP server concepts](https://gofastmcp.com/servers/server)
|
||||||
|
2. [FastMCP resources and resource templates](https://gofastmcp.com/servers/resources)
|
||||||
|
3. [FastMCP resources-as-tools transform](https://gofastmcp.com/servers/transforms/resources-as-tools)
|
||||||
|
4. [MCP specification: resources](https://modelcontextprotocol.io/specification/latest/server/resources)
|
||||||
|
|
||||||
|
Applied conclusions for this step:
|
||||||
|
|
||||||
|
1. Resource contracts remain canonical and should be surfaced directly when clients support resource attachment.
|
||||||
|
2. Tool-first compatibility layers should wrap canonical resource reads rather than creating alternate authored-content stores.
|
||||||
|
3. URI-template-backed resource identity remains stable across direct-resource and tool-compatibility access paths.
|
||||||
|
|
||||||
|
### Client Tool-Naming Research Baseline
|
||||||
|
|
||||||
|
Authoritative and client-specific references to verify during implementation:
|
||||||
|
|
||||||
|
1. [MCP specification: tools](https://modelcontextprotocol.io/specification/latest/server/tools)
|
||||||
|
2. [MCP client concepts](https://modelcontextprotocol.io/docs/learn/client-concepts)
|
||||||
|
3. [FastMCP tools](https://gofastmcp.com/servers/tools)
|
||||||
|
4. [FastMCP resources-as-tools transform](https://gofastmcp.com/servers/transforms/resources-as-tools)
|
||||||
|
5. [VS Code MCP servers](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
||||||
|
6. [VS Code MCP configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration)
|
||||||
|
7. [Cursor MCP documentation](https://docs.cursor.com/context/model-context-protocol)
|
||||||
|
8. [Claude Desktop local MCP server setup](https://support.anthropic.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
||||||
|
|
||||||
|
Baseline naming conclusions:
|
||||||
|
|
||||||
|
1. MCP protocol tool identity is the server-advertised `name` returned by `tools/list` and used in `tools/call`.
|
||||||
|
2. FastMCP tool identity should be treated as the canonical server contract unless a tool is intentionally registered with an explicit alternate name.
|
||||||
|
3. Clients and host integrations may display, namespace, or internally route tool names with provider-specific prefixes, but those wrappers are not canonical server tool names.
|
||||||
|
4. Compatibility should be validated by observed `tools/list` and successful `tools/call` behavior in each target client rather than by assuming one global host naming convention.
|
||||||
|
|
||||||
|
### Discovery Priority Contract (Normative)
|
||||||
|
|
||||||
|
Preferred sequence for skill discovery and loading:
|
||||||
|
|
||||||
|
1. `resource://catalog/skills_index`
|
||||||
|
2. `resource://catalog/skills/{skill_id}`
|
||||||
|
3. `resource://skills/{skill_id}/document`
|
||||||
|
4. `resource://skills/{skill_id}/references/{ref_id}` only when needed
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. Start from catalog discovery before loading any skill document.
|
||||||
|
2. Do not skip straight to broad document loading when catalog metadata can narrow choices first.
|
||||||
|
3. Use `resource://docs/{path*}` only for direct authored-doc access outside skill-specific flows.
|
||||||
|
|
||||||
|
### Fallback Activation Rule
|
||||||
|
|
||||||
|
Fallback is used only when the active client path cannot reliably attach MCP resources (for example, tool-only chat surfaces).
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. Keep the same discovery order semantics as the resource path.
|
||||||
|
2. If resource attachment is available, prefer resources over tools.
|
||||||
|
3. Tool fallback must never become a second authoritative content source.
|
||||||
|
|
||||||
|
### Tool Fallback Surface (Normative)
|
||||||
|
|
||||||
|
The fallback tool surface includes:
|
||||||
|
|
||||||
|
1. `list_resources`
|
||||||
|
2. `read_resource`
|
||||||
|
3. `search_patterns`
|
||||||
|
4. `get_pattern_by_id`
|
||||||
|
5. `get_skill_document_by_id`
|
||||||
|
|
||||||
|
Canonical naming rule:
|
||||||
|
|
||||||
|
1. The server-level tool contract uses the exact registered FastMCP tool names above.
|
||||||
|
2. Clients that expose provider-prefixed names (for example, namespaced wrappers) must map those names to the canonical server tool name before invocation.
|
||||||
|
3. `catalog_get_skill_document_by_id` is not a canonical server tool name for this contract unless an explicit alias is intentionally registered.
|
||||||
|
|
||||||
|
Compatibility alias policy:
|
||||||
|
|
||||||
|
1. Prefer canonical server tool names over aliases.
|
||||||
|
2. Add server-side aliases only when a major client cannot reliably map its wrapper name back to the canonical name.
|
||||||
|
3. Any alias must be read-only, delegate to the same payload builder as the canonical tool, and be documented as compatibility-only.
|
||||||
|
4. If aliases are added, canonical and alias tools must return byte-for-byte equivalent payloads for the same input.
|
||||||
|
|
||||||
|
Fallback order:
|
||||||
|
|
||||||
|
1. call `list_resources` to inspect canonical static/template resource surfaces
|
||||||
|
2. call `read_resource` for catalog URIs and selected skill URIs
|
||||||
|
3. use thin catalog tools only when additional metadata-first narrowing is needed
|
||||||
|
|
||||||
|
Tool behavior requirements:
|
||||||
|
|
||||||
|
1. read-only and idempotent semantics
|
||||||
|
2. deterministic ordering and bounded pagination
|
||||||
|
3. explicit not-found responses (`found: false` style) where applicable
|
||||||
|
4. payloads remain schema-aligned with catalog resources
|
||||||
|
5. tool invocation examples and Copilot guidance must use canonical server tool names to avoid unknown-tool errors
|
||||||
|
|
||||||
|
### Major Client Compatibility Plan
|
||||||
|
|
||||||
|
Target clients and expected validation:
|
||||||
|
|
||||||
|
1. GitHub Copilot in VS Code
|
||||||
|
- primary path: attach MCP resources when `MCP Resources...` is available
|
||||||
|
- fallback path: call `list_resources`, `read_resource`, then canonical thin tools only when needed
|
||||||
|
- validation: confirm Copilot-visible tool inventory includes or can invoke `list_resources`, `read_resource`, `search_patterns`, `get_pattern_by_id`, and `get_skill_document_by_id`
|
||||||
|
- compatibility risk: host-generated wrapper names may differ from canonical FastMCP names; document any observed wrapper-to-canonical mapping
|
||||||
|
2. Cursor
|
||||||
|
- primary path: use the client MCP server configuration and resource/tool surfaces supported by the active Cursor version
|
||||||
|
- fallback path: prefer resource-backed tools first, then canonical thin tools
|
||||||
|
- validation: capture Cursor `tools/list` equivalent behavior and verify the canonical tool names or required host mappings
|
||||||
|
- compatibility risk: Cursor may present MCP tools through its own UI labels or internal routing names
|
||||||
|
3. Claude Desktop
|
||||||
|
- primary path: configure the local MCP server and inspect advertised tools/resources in Claude Desktop
|
||||||
|
- fallback path: invoke canonical server tool names exactly as returned by `tools/list`
|
||||||
|
- validation: run a local smoke prompt that reads `resource://catalog/skills_index` and loads one skill document through `read_resource` or `get_skill_document_by_id`
|
||||||
|
- compatibility risk: local server configuration and transport setup may fail before tool-name compatibility is tested
|
||||||
|
4. Generic MCP clients and SDK-based tests
|
||||||
|
- primary path: protocol-level `resources/list`, `resources/read`, `tools/list`, and `tools/call`
|
||||||
|
- fallback path: none beyond the canonical tool contract
|
||||||
|
- validation: automated smoke tests assert exact tool names returned by `tools/list` and successful calls for canonical names
|
||||||
|
- compatibility risk: SDK/client libraries may expose helper names that differ from raw protocol names
|
||||||
|
|
||||||
|
Implementation checklist:
|
||||||
|
|
||||||
|
1. Capture each target client's advertised tool names before adding aliases.
|
||||||
|
2. Prefer fixing documentation or client-side mapping when the server already advertises canonical names correctly.
|
||||||
|
3. Add a server-side alias only for a confirmed major-client incompatibility.
|
||||||
|
4. Add regression tests for canonical names, resource-backed tools, and any intentionally supported aliases.
|
||||||
|
5. Keep public examples centered on `list_resources`/`read_resource` and canonical thin tool names.
|
||||||
|
|
||||||
|
### Resources-As-Tools Compatibility Layer
|
||||||
|
|
||||||
|
Step 6 includes a resources-as-tools compatibility layer for clients that can call tools but not attach resources.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. It wraps canonical resource reads rather than re-implementing content transforms.
|
||||||
|
2. It preserves canonical URIs and metadata semantics.
|
||||||
|
3. It does not replace the minimal catalog tools listed above.
|
||||||
|
4. It is interoperability-driven and remains read-only.
|
||||||
|
|
||||||
|
### Resource/Tool Parity Contract
|
||||||
|
|
||||||
|
Resources and fallback tools must agree on identity and routing metadata.
|
||||||
|
|
||||||
|
Parity requirements:
|
||||||
|
|
||||||
|
1. `skill_id` and `ref_id` are identical across both paths.
|
||||||
|
2. canonical URIs in payloads match Step 3 URI rules.
|
||||||
|
3. skill metadata (`id`, `name`, `description`, `tags`, `capabilities`, `version`) remains consistent.
|
||||||
|
4. document payload returned by `get_skill_document_by_id` resolves to the same canonical `SKILL.md` content as `resource://skills/{skill_id}/document`.
|
||||||
|
|
||||||
|
### Relevance and Ranking Contract
|
||||||
|
|
||||||
|
Baseline matching behavior is metadata-first and deterministic.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. Search primarily over normalized skill metadata (id, name, description, tags).
|
||||||
|
2. Keep deterministic ordering and deterministic pagination behavior.
|
||||||
|
3. Keep ranking logic transparent and bounded for predictable client behavior.
|
||||||
|
|
||||||
|
Optional extension policy:
|
||||||
|
|
||||||
|
1. BM25/regex augmentation is allowed only when catalog/tool volume meaningfully harms token efficiency or precision.
|
||||||
|
2. Any augmentation must preserve canonical ids, URIs, and deterministic tie-breaking.
|
||||||
|
3. Any augmentation remains discovery-only and does not create alternate content payloads.
|
||||||
|
|
||||||
|
### Context-Bounding and Clarification Policy
|
||||||
|
|
||||||
|
To prevent context bloat and improve answer quality:
|
||||||
|
|
||||||
|
1. load only the most relevant skill document by default
|
||||||
|
2. load at most two skill documents in one pass unless the user explicitly asks for more
|
||||||
|
3. if confidence is low after catalog discovery, ask one clarifying question before loading additional skill documents
|
||||||
|
4. fetch references lazily and only when required
|
||||||
|
|
||||||
|
### Security and Safety Constraints
|
||||||
|
|
||||||
|
Fallback tools must preserve the project security invariant.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. tool surfaces stay documentation-only and read-only
|
||||||
|
2. no mutation, shell execution, secret access, or private filesystem exposure
|
||||||
|
3. all returned content remains safe to publish publicly
|
||||||
|
|
||||||
|
### Integration Boundaries
|
||||||
|
|
||||||
|
Step 6 integrates with prior steps as follows:
|
||||||
|
|
||||||
|
1. Step 4 provides the validated in-memory registry.
|
||||||
|
2. Step 5 provides canonical resource registration.
|
||||||
|
3. Step 6 adds fallback discovery/read behavior that reuses the same registry and canonical markdown sources.
|
||||||
|
|
||||||
|
Separation-of-concerns rule:
|
||||||
|
|
||||||
|
1. Catalog/resource contracts remain canonical.
|
||||||
|
2. Fallback tools are interoperability adapters, not a parallel architecture.
|
||||||
|
|
||||||
|
### Acceptance Criteria for Step 6 Completion
|
||||||
|
|
||||||
|
Step 6 is complete when all are true:
|
||||||
|
|
||||||
|
1. Resource-first discovery remains the documented and implemented default path.
|
||||||
|
2. `list_resources` and `read_resource` are available for tool-only clients.
|
||||||
|
3. Thin catalog tools remain minimal, read-only parity surfaces.
|
||||||
|
4. Fallback tool outputs map to canonical skill identities and URIs.
|
||||||
|
5. Context loading is bounded and clarifying-question behavior is documented for low-confidence cases.
|
||||||
|
6. No second content source is introduced; resources and tools resolve the same authored markdown.
|
||||||
|
|
||||||
|
### Non-goals for Step 6
|
||||||
|
|
||||||
|
1. No write or side-effecting tools.
|
||||||
|
2. No alternate authored markdown stores or duplicated skill content pipelines.
|
||||||
|
3. No guarantee that every client session exposes MCP resource attachment UI.
|
||||||
|
4. No packaging/build contract changes (handled in Step 7).
|
||||||
|
5. No CI gate expansion details (handled in later validation/governance steps).
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
---
|
|
||||||
name: Pytest Fill Scaffold
|
|
||||||
description: Fill scaffolded pytest test methods with assertions, fixtures, and minimal test data while preserving concise test names and one-line intent docstrings.
|
|
||||||
argument-hint: Target test file(s) under tests plus stack (pure-python, fastapi, sqlalchemy-sync, sqlalchemy-async, or mixed)
|
|
||||||
agent: agent
|
|
||||||
---
|
|
||||||
|
|
||||||
# Pytest Fill Scaffold
|
|
||||||
|
|
||||||
Use this prompt after test scaffolding exists and method names/docstrings are already in place.
|
|
||||||
|
|
||||||
## Inputs
|
|
||||||
|
|
||||||
- Target test file(s) under `tests/`.
|
|
||||||
- Stack type:
|
|
||||||
- `pure-python`
|
|
||||||
- `fastapi`
|
|
||||||
- `sqlalchemy-sync`
|
|
||||||
- `sqlalchemy-async`
|
|
||||||
- `mixed`
|
|
||||||
- Optional constraints:
|
|
||||||
- keep implementation minimal vs comprehensive
|
|
||||||
- marker lane target (`unit`, `integration`, `smoke`)
|
|
||||||
|
|
||||||
## Required References
|
|
||||||
|
|
||||||
Load these in order and use only what matches the task:
|
|
||||||
|
|
||||||
1. Core defaults: [pytest scaffolding skill](../../src/personal_mcp/docs/skills/pytesting/SKILL.md)
|
|
||||||
2. Naming/hierarchy preservation: [naming and organization](../../src/personal_mcp/docs/skills/pytesting/references/naming-and-organization.md)
|
|
||||||
3. Baseline pytest fixtures/markers: [pytest docs notes](../../src/personal_mcp/docs/skills/pytesting/references/pytest-docs.md)
|
|
||||||
4. FastAPI-specific behavior (only when needed): [fastapi testing](../../src/personal_mcp/docs/skills/pytesting/references/fastapi-testing.md)
|
|
||||||
5. SQLAlchemy-specific behavior (only when needed): [sqlalchemy testing](../../src/personal_mcp/docs/skills/pytesting/references/sqlalchemy-testing.md)
|
|
||||||
|
|
||||||
## Workflow
|
|
||||||
|
|
||||||
1. Inspect target files and treat human-reviewed docstring-only scaffolds as invariant.
|
|
||||||
2. Convert each scaffolded method into an executable test with a single behavior focus.
|
|
||||||
3. Keep one-line docstrings for class and method intent.
|
|
||||||
4. Add or refine fixtures at the nearest useful scope:
|
|
||||||
- global in `tests/conftest.py` only when broadly reusable
|
|
||||||
- subtree `conftest.py` for domain-specific fixtures
|
|
||||||
5. Assign markers consistent with cost and dependencies:
|
|
||||||
- `unit` for pure logic
|
|
||||||
- `integration` for framework/DB contracts
|
|
||||||
- `smoke` for thin critical-path checks
|
|
||||||
6. Validate in this order:
|
|
||||||
- `uv run pytest --collect-only -q`
|
|
||||||
- `uv run pytest -m unit -q` when unit tests are touched
|
|
||||||
- `uv run pytest -q` if dependencies are available
|
|
||||||
|
|
||||||
## Authoring Rules
|
|
||||||
|
|
||||||
- Prefer deterministic tests and explicit setup/teardown.
|
|
||||||
- Keep assertions precise and readable.
|
|
||||||
- Do not overfit tests to private implementation details.
|
|
||||||
- If a scaffolded class or method has only a docstring body, treat its name and hierarchy as locked.
|
|
||||||
- Do not rename, move, merge, split, or re-nest docstring-only scaffolded tests unless explicitly requested.
|
|
||||||
- Preserve existing one-line docstrings on scaffolded classes and methods unless they are factually incorrect.
|
|
||||||
- If stack details are missing and would change fixture strategy, ask one concise clarifying question before editing.
|
|
||||||
|
|
||||||
## Output Format
|
|
||||||
|
|
||||||
Return:
|
|
||||||
1. Files updated.
|
|
||||||
2. Fixture and marker decisions.
|
|
||||||
3. Which references were used and why.
|
|
||||||
4. Validation command results.
|
|
||||||
5. Risks or open questions.
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
---
|
|
||||||
name: Pytest Scaffold
|
|
||||||
description: Plan and scaffold pytest test files, class hierarchy, and concise method names for selected Python modules in this repository.
|
|
||||||
argument-hint: Target module path(s) in src plus scope (plan-only or scaffold)
|
|
||||||
agent: agent
|
|
||||||
---
|
|
||||||
|
|
||||||
# Pytest Scaffold
|
|
||||||
|
|
||||||
Use this prompt to do in one run what we have been doing manually in chat:
|
|
||||||
1. Build a naming and hierarchy plan for tests.
|
|
||||||
2. Scaffold test files and class/method skeletons.
|
|
||||||
3. Keep test method names concise because intent is carried by one-line docstrings.
|
|
||||||
|
|
||||||
## Inputs
|
|
||||||
|
|
||||||
- Target module path(s) under `src/`.
|
|
||||||
- Scope mode:
|
|
||||||
- `plan-only`
|
|
||||||
- `scaffold`
|
|
||||||
- Optional constraints:
|
|
||||||
- flattening preferences for path mapping under `tests/`
|
|
||||||
- method naming style preference
|
|
||||||
|
|
||||||
## Repository Rules To Apply
|
|
||||||
|
|
||||||
- Use [pytest scaffolding skill](../../src/personal_mcp/docs/skills/pytesting/SKILL.md) for strategy and defaults.
|
|
||||||
- Use [naming and organization reference](../../src/personal_mcp/docs/skills/pytesting/references/naming-and-organization.md) before finalizing hierarchy.
|
|
||||||
- Use `uv run pytest --collect-only -q` as structural validation.
|
|
||||||
- Default to a source-mirror style adapted to this repository:
|
|
||||||
- map selected modules to `tests/` with concise path segments when requested
|
|
||||||
- keep one test module per source module
|
|
||||||
|
|
||||||
## Execution Steps
|
|
||||||
|
|
||||||
1. Inspect current `tests/` layout and identify existing naming patterns.
|
|
||||||
2. Propose a concise hierarchy plan first:
|
|
||||||
- test file paths
|
|
||||||
- class hierarchy
|
|
||||||
- method naming pattern
|
|
||||||
- fixture placement (`tests/conftest.py` vs subtree `conftest.py`)
|
|
||||||
3. If scope mode is `scaffold`, implement the skeleton:
|
|
||||||
- create missing test modules
|
|
||||||
- create class hierarchy
|
|
||||||
- add one-line docstrings to every class and test method
|
|
||||||
- keep test method names short and behavior-focused
|
|
||||||
- treat resulting docstring-only scaffolds as human-reviewed baseline for future fill-in work
|
|
||||||
4. Validate collection with `uv run pytest --collect-only -q`.
|
|
||||||
5. Report results:
|
|
||||||
- files created or updated
|
|
||||||
- collection outcome
|
|
||||||
- any ambiguities or follow-up choices
|
|
||||||
|
|
||||||
## Class And Method Shape Defaults
|
|
||||||
|
|
||||||
- Class shape:
|
|
||||||
- `Test<PrimarySubject>` as the top-level subject class
|
|
||||||
- nested `Test<MethodOrArea>` classes when it improves context
|
|
||||||
- top-level `Test<FunctionName>` classes for standalone module functions
|
|
||||||
- Method shape:
|
|
||||||
- `test_<short_outcome>` naming
|
|
||||||
- one behavior target per method name
|
|
||||||
- one-line docstring that states the full intent
|
|
||||||
|
|
||||||
## Output Format
|
|
||||||
|
|
||||||
Return:
|
|
||||||
1. Discovery summary and references consulted.
|
|
||||||
2. Proposed or applied test tree.
|
|
||||||
3. Class and method naming map.
|
|
||||||
4. Validation command results.
|
|
||||||
5. Open questions only if they block confident completion.
|
|
||||||
@@ -1,183 +0,0 @@
|
|||||||
## Goal
|
|
||||||
|
|
||||||
Build a local, self-hosted documentation knowledge base that can ingest software docs, generate embeddings, store them in SQLite, and expose high-quality retrieval through MCP tools and resources.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Core Architectural Decisions
|
|
||||||
|
|
||||||
### Storage
|
|
||||||
|
|
||||||
Use:
|
|
||||||
|
|
||||||
* SQLite for metadata and document storage
|
|
||||||
* FTS5 for keyword search
|
|
||||||
* sqlite-vec for vector similarity search
|
|
||||||
|
|
||||||
Avoid a separate vector database unless scale requirements emerge.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Embeddings
|
|
||||||
|
|
||||||
Use local embedding models via:
|
|
||||||
|
|
||||||
* sentence-transformers
|
|
||||||
|
|
||||||
Recommended model:
|
|
||||||
|
|
||||||
```text
|
|
||||||
BAAI/bge-base-en-v1.5
|
|
||||||
```
|
|
||||||
|
|
||||||
Store embeddings alongside document chunks.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Ingestion
|
|
||||||
|
|
||||||
Primary sources:
|
|
||||||
|
|
||||||
1. Git repositories containing Markdown docs
|
|
||||||
2. Documentation websites via Crawl4AI
|
|
||||||
3. Sitemap-driven crawls when available
|
|
||||||
|
|
||||||
Pipeline:
|
|
||||||
|
|
||||||
```text
|
|
||||||
Source
|
|
||||||
↓
|
|
||||||
Extract
|
|
||||||
↓
|
|
||||||
Normalize
|
|
||||||
↓
|
|
||||||
Chunk by headings
|
|
||||||
↓
|
|
||||||
Embed
|
|
||||||
↓
|
|
||||||
Store
|
|
||||||
```
|
|
||||||
|
|
||||||
Track content hashes so unchanged documents are skipped during reindexing.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Retrieval
|
|
||||||
|
|
||||||
Implement hybrid retrieval:
|
|
||||||
|
|
||||||
```text
|
|
||||||
FTS5 keyword search
|
|
||||||
+
|
|
||||||
sqlite-vec similarity search
|
|
||||||
↓
|
|
||||||
Candidate set
|
|
||||||
↓
|
|
||||||
Reranker
|
|
||||||
↓
|
|
||||||
Final results
|
|
||||||
```
|
|
||||||
|
|
||||||
Reranker:
|
|
||||||
|
|
||||||
```text
|
|
||||||
BAAI/bge-reranker-v2
|
|
||||||
```
|
|
||||||
|
|
||||||
The retriever owns all ranking logic.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Public Interface
|
|
||||||
|
|
||||||
Do not expose vector search directly.
|
|
||||||
|
|
||||||
Expose a retrieval service through MCP:
|
|
||||||
|
|
||||||
```python
|
|
||||||
search_docs(query)
|
|
||||||
|
|
||||||
get_context(query)
|
|
||||||
|
|
||||||
get_doc(path)
|
|
||||||
```
|
|
||||||
|
|
||||||
The MCP layer becomes the stable API.
|
|
||||||
|
|
||||||
Clients never interact with embeddings or vectors.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Repository Layout
|
|
||||||
|
|
||||||
```text
|
|
||||||
src/
|
|
||||||
├── knowledge/
|
|
||||||
│ ├── models.py
|
|
||||||
│ ├── chunking.py
|
|
||||||
│ ├── embeddings.py
|
|
||||||
│ ├── ingestion.py
|
|
||||||
│ ├── sqlite_store.py
|
|
||||||
│ ├── hybrid_search.py
|
|
||||||
│ ├── reranker.py
|
|
||||||
│ └── retrieval.py
|
|
||||||
│
|
|
||||||
├── sources/
|
|
||||||
│ ├── git_docs.py
|
|
||||||
│ ├── crawl4ai_docs.py
|
|
||||||
│ └── sitemap_docs.py
|
|
||||||
│
|
|
||||||
├── mcp_server/
|
|
||||||
│ ├── tools.py
|
|
||||||
│ └── resources.py
|
|
||||||
│
|
|
||||||
└── cli/
|
|
||||||
├── ingest.py
|
|
||||||
└── reindex.py
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Retrieval Flow
|
|
||||||
|
|
||||||
```text
|
|
||||||
User Query
|
|
||||||
↓
|
|
||||||
Embed Query
|
|
||||||
↓
|
|
||||||
FTS5 Search
|
|
||||||
+
|
|
||||||
Vector Search
|
|
||||||
↓
|
|
||||||
Merge Results
|
|
||||||
↓
|
|
||||||
Rerank
|
|
||||||
↓
|
|
||||||
Return Context Bundle
|
|
||||||
```
|
|
||||||
|
|
||||||
Where a context bundle contains:
|
|
||||||
|
|
||||||
```python
|
|
||||||
ContextBundle(
|
|
||||||
passages=[...],
|
|
||||||
citations=[...],
|
|
||||||
related_docs=[...],
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Future Extensions
|
|
||||||
|
|
||||||
Without changing the architecture:
|
|
||||||
|
|
||||||
* Multiple documentation corpora
|
|
||||||
* Version-aware retrieval
|
|
||||||
* Code snippet indexing
|
|
||||||
* MCP resources for specific topics
|
|
||||||
* LangGraph integration
|
|
||||||
* Docker deployment
|
|
||||||
* Scheduled reindexing
|
|
||||||
|
|
||||||
The key design principle is: **treat the vector store as an internal implementation detail and expose a retrieval-oriented MCP interface instead.**
|
|
||||||
Vendored
-18
@@ -1,18 +0,0 @@
|
|||||||
{
|
|
||||||
"version": "0.2.0",
|
|
||||||
"configurations": [
|
|
||||||
{
|
|
||||||
"name": "Python: personal-mcp entrypoint",
|
|
||||||
"type": "debugpy",
|
|
||||||
"request": "launch",
|
|
||||||
"module": "personal_mcp.__main__",
|
|
||||||
"cwd": "${workspaceFolder}",
|
|
||||||
"console": "integratedTerminal",
|
|
||||||
"justMyCode": true,
|
|
||||||
"env": {
|
|
||||||
"PYTHONUNBUFFERED": "1"
|
|
||||||
},
|
|
||||||
"args": [ "--port", "8766", "--reload" ]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
Vendored
+6
-1
@@ -51,7 +51,12 @@
|
|||||||
"command": "uv",
|
"command": "uv",
|
||||||
"args": [
|
"args": [
|
||||||
"run",
|
"run",
|
||||||
"personal-mcp",
|
"uvicorn",
|
||||||
|
"personal_mcp.main:app",
|
||||||
|
"--host",
|
||||||
|
"127.0.0.1",
|
||||||
|
"--port",
|
||||||
|
"8000",
|
||||||
"--reload"
|
"--reload"
|
||||||
],
|
],
|
||||||
"options": {
|
"options": {
|
||||||
|
|||||||
+28
-26
@@ -1,52 +1,54 @@
|
|||||||
FROM python:3.14-slim AS builder
|
FROM python:3.14-slim AS builder
|
||||||
|
|
||||||
ENV PYTHONUNBUFFERED=1 \
|
|
||||||
UV_SYSTEM_CERTS=1 \
|
|
||||||
UV_PYTHON_DOWNLOADS=0 \
|
|
||||||
UV_NO_MANAGED_PYTHON=1 \
|
|
||||||
UV_SYSTEM_PYTHON=1 \
|
|
||||||
UV_PROJECT_ENVIRONMENT=/usr/local \
|
|
||||||
UV_COMPILE_BYTECODE=1 \
|
|
||||||
UV_NO_DEV=1 \
|
|
||||||
UV_LOCKED=1 \
|
|
||||||
UV_LINK_MODE=copy
|
|
||||||
|
|
||||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
UV_COMPILE_BYTECODE=1 \
|
||||||
|
UV_LINK_MODE=copy \
|
||||||
|
UV_LOCKED=1
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
--mount=type=bind,source=zensical.toml,target=zensical.toml \
|
--mount=type=bind,source=zensical.toml,target=zensical.toml \
|
||||||
--mount=type=bind,source=src/personal_mcp/docs/,target=src/personal_mcp/docs/ \
|
--mount=type=bind,source=docs/,target=docs/ \
|
||||||
uvx zensical build --clean --strict
|
uvx zensical build
|
||||||
|
|
||||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
--mount=type=bind,source=uv.lock,target=uv.lock \
|
--mount=type=bind,source=uv.lock,target=uv.lock \
|
||||||
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
||||||
uv sync --no-install-project
|
uv sync --no-install-project
|
||||||
|
|
||||||
COPY pyproject.toml uv.lock README.md /app/
|
# COPY --chown=appuser:appuser . /app
|
||||||
COPY ./src /app/src
|
|
||||||
|
|
||||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
# RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
uv sync
|
# uv sync --no-editable
|
||||||
|
|
||||||
FROM python:3.14-slim AS runtime
|
FROM python:3.14-slim AS runtime
|
||||||
|
|
||||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
PYTHONUNBUFFERED=1
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PATH="/app/.venv/bin:$PATH" \
|
||||||
|
PERSONAL_MCP_MOUNTS__DOCS_DIR=/app/docs
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
EXPOSE 8765
|
||||||
|
|
||||||
RUN groupadd --system --gid 1001 appuser && \
|
RUN groupadd --system --gid 1001 appuser && \
|
||||||
useradd --system --uid 1001 --gid appuser appuser
|
useradd --system --uid 1001 --gid appuser appuser
|
||||||
|
|
||||||
WORKDIR /app
|
COPY --from=ghcr.io/astral-sh/uv:latest --chown=appuser:appuser /uv /uvx /bin/
|
||||||
|
COPY --from=builder --chown=appuser:appuser /app/.venv /app/.venv
|
||||||
|
COPY --from=builder --chown=appuser:appuser /app/site /app/site
|
||||||
|
COPY --chown=appuser:appuser ./docs /app/docs
|
||||||
|
|
||||||
RUN chown appuser:appuser /app
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
|
--mount=type=bind,source=uv.lock,target=uv.lock \
|
||||||
COPY --from=builder --chown=appuser:appuser /usr/local/lib /usr/local/lib
|
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
||||||
COPY --from=builder --chown=appuser:appuser /usr/local/bin /usr/local/bin
|
--mount=type=bind,source=src/,target=src/ \
|
||||||
COPY --from=builder --chown=appuser:appuser /app /app
|
uv sync --no-editable
|
||||||
|
|
||||||
USER appuser
|
USER appuser
|
||||||
|
|
||||||
ENTRYPOINT ["/usr/local/bin/personal-mcp"]
|
CMD ["uvicorn", "personal_mcp.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8765"]
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
# JSL MCP
|
|
||||||
|
|
||||||
```shell
|
|
||||||
uv run mcp-stdio
|
|
||||||
```
|
|
||||||
|
|
||||||
```shell
|
|
||||||
uv run fastmcp list --command "uv run mcp-stdio" --prompts
|
|
||||||
```
|
|
||||||
|
|
||||||
```shell
|
|
||||||
uv run fastmcp call --command "uv run mcp-stdio" \
|
|
||||||
--target authoring --prompt \
|
|
||||||
--input-json '{"artifact_type":"prompt","artifact_id":"release-notes","goal":"Create a reusable release-notes workflow."}' \
|
|
||||||
--json
|
|
||||||
```
|
|
||||||
+5
-10
@@ -1,13 +1,8 @@
|
|||||||
services:
|
services:
|
||||||
app:
|
personal-mcp:
|
||||||
image: personal-mcp:latest
|
build:
|
||||||
build: .
|
context: .
|
||||||
restart: unless-stopped
|
dockerfile: Dockerfile
|
||||||
ports:
|
ports:
|
||||||
- "8765:8765"
|
- "8765:8765"
|
||||||
environment:
|
restart: unless-stopped
|
||||||
PERSONAL_MCP_PORT: 8765
|
|
||||||
PERSONAL_MCP_HOST: 0.0.0.0
|
|
||||||
PERSONAL_MCP_RELOAD: 1
|
|
||||||
volumes:
|
|
||||||
- ./src:/app/src:ro
|
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/library
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architecture
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The platform is implemented as a resource-first MCP system with an integrated static documentation surface. The same methodology content powers both MCP resources and the published docs site.
|
||||||
|
|
||||||
|
An MCP server is a runtime that exposes machine-readable resources and tools through stable interfaces so AI clients can discover and consume context consistently. Here, the server's role is intentionally narrow: publish canonical methodology documents as resources, keep discovery predictable through a catalog layer, and serve the same source material as pre-built static documentation.
|
||||||
|
|
||||||
|
The system is complete in three layers:
|
||||||
|
|
||||||
|
1. Canonical methodology is maintained in Markdown skill documents.
|
||||||
|
2. Catalog resources provide normalized discovery.
|
||||||
|
3. Zensical builds a static site from those same Markdown sources and the FastAPI app serves it in the FastMCP runtime process.
|
||||||
|
|
||||||
|
Prompt documents under `docs/prompts/` are also indexed and exposed as first-class catalog and prompt surfaces.
|
||||||
|
|
||||||
|
This architecture is anchored by three contracts:
|
||||||
|
|
||||||
|
1. Docs-first authored content contract under `docs/` with strict per-skill ownership.
|
||||||
|
2. `SKILL.md` frontmatter contract with Anthropic fields plus `x-personal-mcp` metadata.
|
||||||
|
3. Canonical resource URI contract with break-and-replace policy for contract changes.
|
||||||
|
|
||||||
|
Detailed contract pages:
|
||||||
|
|
||||||
|
1. [Content Contract](./contracts/index.md#content-contract)
|
||||||
|
2. [Frontmatter Contract](./contracts/frontmatter.md)
|
||||||
|
3. [URI Contract](./contracts/uris.md)
|
||||||
|
|
||||||
|
This architecture keeps authored content human-friendly while preserving machine-stable contracts.
|
||||||
|
|
||||||
|
## Intent
|
||||||
|
|
||||||
|
The architecture is designed to satisfy three long-term requirements:
|
||||||
|
|
||||||
|
1. Methodology must be editable as markdown by humans.
|
||||||
|
2. Agents must consume stable, discoverable resource contracts, with a minimal read-only catalog tool fallback for constrained clients.
|
||||||
|
3. Public documentation must be pre-built static output served from the application runtime without a separate docs service.
|
||||||
|
|
||||||
|
## System Model
|
||||||
|
|
||||||
|
### Pattern Modules
|
||||||
|
|
||||||
|
Each skill encapsulates one methodology domain in a docs-owned directory:
|
||||||
|
|
||||||
|
1. `docs/skills/<skill-id>/SKILL.md`
|
||||||
|
2. `docs/skills/<skill-id>/references/...`
|
||||||
|
|
||||||
|
The skill document and references are the authored source of truth; runtime code indexes and serves these files without becoming a second authored source.
|
||||||
|
|
||||||
|
Each skill publishes resource families:
|
||||||
|
|
||||||
|
1. document
|
||||||
|
|
||||||
|
The document resource returns canonical Markdown, while clients can perform any downstream section extraction they need.
|
||||||
|
|
||||||
|
### Prompt Modules
|
||||||
|
|
||||||
|
Prompt guidance can be authored in `docs/prompts/` using either canonical prompt directories (`docs/prompts/<prompt-id>/PROMPT.md`) or legacy markdown files during migration.
|
||||||
|
|
||||||
|
Prompt modules publish two additive surfaces:
|
||||||
|
|
||||||
|
1. prompt resources for catalog and document retrieval
|
||||||
|
2. MCP prompt objects for prompt-list/get-prompt style client workflows
|
||||||
|
|
||||||
|
This keeps authored markdown as source-of-truth while allowing clients to discover and invoke prompts directly.
|
||||||
|
|
||||||
|
### Catalog Module
|
||||||
|
|
||||||
|
The catalog is the canonical discovery layer and publishes normalized records for all modules. It may also expose a minimal set of read-only discovery tools that resolve back to the same canonical markdown content when a client chat surface does not expose MCP resource attachment.
|
||||||
|
|
||||||
|
Typical catalog resources:
|
||||||
|
|
||||||
|
1. resource://catalog/skills_index
|
||||||
|
2. resource://catalog/skills_index{?q,tag,capability,cursor,limit}
|
||||||
|
3. resource://catalog/skills/{skill_id}
|
||||||
|
4. resource://catalog/prompts_index
|
||||||
|
5. resource://catalog/prompts_index{?q,tag,cursor,limit}
|
||||||
|
6. resource://catalog/prompts/{prompt_id}
|
||||||
|
|
||||||
|
Only canonical catalog resources are part of the runtime contract in this phase.
|
||||||
|
|
||||||
|
### Registry Loader
|
||||||
|
|
||||||
|
Importing the package does not read or parse documentation. The MCP server and FastAPI application factories request the registry when constructing a runnable server, using packaged resources through `importlib.resources.files(...)` and `Traversable` APIs.
|
||||||
|
|
||||||
|
Loader responsibilities:
|
||||||
|
|
||||||
|
1. Parse SKILL.md frontmatter for each skill.
|
||||||
|
2. Validate schema and cross-field constraints before any resource registration.
|
||||||
|
3. Build an in-memory registry keyed by `skill_id`.
|
||||||
|
4. Fail fast for duplicate ids, missing markdown files, and broken reference mappings.
|
||||||
|
|
||||||
|
The immutable registry is cached for the process lifetime. Each Uvicorn worker constructs and retains its own registry because worker processes do not share Python objects. Registry load failure is a server-factory startup error, not a package-import error or partial runtime warning.
|
||||||
|
|
||||||
|
### Content Sources
|
||||||
|
|
||||||
|
Content is authored in markdown under `docs/` and managed as long-form reference material. Skill documents and companion references now live under `docs/skills/`, while project-authored pages remain alongside them in the docs tree. Resource handlers expose the same authored documents through stable resource URIs.
|
||||||
|
|
||||||
|
The repository root `docs/` directory is the only authored source. The `src/personal_mcp/docs` path is a relative symlink to that directory for source-checkout and editable-install workflows; it is not a second content tree and packaging does not depend on traversing it.
|
||||||
|
|
||||||
|
For wheel builds, [Hatchling forced inclusion](https://hatch.pypa.io/latest/config/build/#forced-inclusion) maps the root `docs/` tree to `personal_mcp/docs/`. The wheel therefore contains regular resource files at that destination rather than a symlink. Runtime registry loading uses [`importlib.resources.files`](https://docs.python.org/3/library/importlib.resources.html#importlib.resources.files) and `Traversable` operations from the `personal_mcp` package anchor, so it does not depend on the repository layout or current working directory.
|
||||||
|
|
||||||
|
### Static Docs Surface
|
||||||
|
|
||||||
|
Static docs are built directly from two markdown source streams:
|
||||||
|
|
||||||
|
1. Project-authored docs pages
|
||||||
|
2. Skill and reference markdown pages
|
||||||
|
|
||||||
|
The merged docs tree is built by Zensical into static files and served by the FastAPI app.
|
||||||
|
|
||||||
|
Generated `site/` files are deployment assets for the human-facing static site. They are separate from the authored Markdown resources packaged under `personal_mcp/docs/`.
|
||||||
|
|
||||||
|
## Data Flow
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[Authored Markdown] --> C[Resource Handlers]
|
||||||
|
B[Pattern Metadata] --> D[Catalog Resources]
|
||||||
|
A --> E[Zensical Static Build]
|
||||||
|
E --> H[FastAPI Static Mount]
|
||||||
|
H --> I[Served Docs Site]
|
||||||
|
D --> I
|
||||||
|
```
|
||||||
|
|
||||||
|
## Contracts
|
||||||
|
|
||||||
|
### Metadata Contract
|
||||||
|
|
||||||
|
Each skill declares frontmatter in `docs/skills/<skill-id>/SKILL.md`.
|
||||||
|
|
||||||
|
For the full field-level contract, validation model, and FastMCP metadata mapping, see [Frontmatter Contract](./contracts/frontmatter.md).
|
||||||
|
|
||||||
|
Anthropic-facing required fields:
|
||||||
|
|
||||||
|
1. name
|
||||||
|
2. description
|
||||||
|
|
||||||
|
Repository indexing metadata is declared in `x-personal-mcp`:
|
||||||
|
|
||||||
|
1. id
|
||||||
|
2. version
|
||||||
|
3. tags
|
||||||
|
4. capabilities
|
||||||
|
5. optional references map (for nested entries, overrides, and aliases)
|
||||||
|
|
||||||
|
No `metadata.yaml` sidecar is part of the end-state contract.
|
||||||
|
|
||||||
|
### URI Contract
|
||||||
|
|
||||||
|
Canonical resource URIs are:
|
||||||
|
|
||||||
|
For the full URI semantics, parameter validation rules, and compatibility policy, see [URI Contract](./contracts/uris.md).
|
||||||
|
|
||||||
|
1. resource://skills/<skill_id>/document
|
||||||
|
2. resource://skills/<skill_id>/references/<ref_id>
|
||||||
|
3. resource://catalog/skills_index
|
||||||
|
4. resource://catalog/skills_index{?q,tag,capability,cursor,limit}
|
||||||
|
5. resource://catalog/skills/{skill_id}
|
||||||
|
6. resource://docs/{path*}
|
||||||
|
7. resource://catalog/prompts_index
|
||||||
|
8. resource://catalog/prompts_index{?q,tag,cursor,limit}
|
||||||
|
9. resource://catalog/prompts/{prompt_id}
|
||||||
|
10. resource://prompts/{prompt_id}/document
|
||||||
|
|
||||||
|
Validation rules:
|
||||||
|
|
||||||
|
1. `skill_id` is lowercase kebab-case and must satisfy the stable skill id contract.
|
||||||
|
2. `ref_id` is lowercase kebab-case and must resolve from either:
|
||||||
|
- top-level auto-discovery of `references/*.md` filename stems, or
|
||||||
|
- an explicit `x-personal-mcp.references` entry.
|
||||||
|
3. `path*` resolves only to normalized markdown paths under `docs/`.
|
||||||
|
|
||||||
|
### Resource Registration Contract
|
||||||
|
|
||||||
|
Resources are registered from the validated registry, not by ad hoc per-skill hardcoding.
|
||||||
|
|
||||||
|
Registration rules:
|
||||||
|
|
||||||
|
1. Use RFC6570 URI templates where appropriate.
|
||||||
|
2. Mark documentation resources as read-only and idempotent.
|
||||||
|
3. Set explicit mime types for resource responses.
|
||||||
|
4. Configure duplicate URI handling with `on_duplicate="error"` for startup safety.
|
||||||
|
|
||||||
|
This keeps runtime behavior deterministic and prevents accidental URI collisions.
|
||||||
|
|
||||||
|
### Versioning Rule
|
||||||
|
|
||||||
|
URIs are unversioned and canonical in this phase.
|
||||||
|
|
||||||
|
1. Breaking URI changes are handled as direct replacement.
|
||||||
|
2. No compatibility aliases or dual URI families are maintained.
|
||||||
|
|
||||||
|
## Static Hosting Pattern
|
||||||
|
|
||||||
|
The docs site is pre-built and served by the same FastAPI runtime process used by the MCP app.
|
||||||
|
|
||||||
|
Runtime behavior:
|
||||||
|
|
||||||
|
1. App starts.
|
||||||
|
2. FastAPI mounts the static docs output directory.
|
||||||
|
3. Requests to docs paths are served as static assets.
|
||||||
|
|
||||||
|
This provides a single deployment artifact with no runtime markdown rendering dependency.
|
||||||
|
|
||||||
|
## Advantages
|
||||||
|
|
||||||
|
### Single Source of Truth
|
||||||
|
|
||||||
|
Methodology is authored once and reused in both MCP resources and docs pages.
|
||||||
|
|
||||||
|
### High-Fidelity Agent Context
|
||||||
|
|
||||||
|
Resources expose the same canonical Markdown that humans author and review.
|
||||||
|
|
||||||
|
### Operational Simplicity
|
||||||
|
|
||||||
|
A single app process serves MCP and docs surfaces.
|
||||||
|
|
||||||
|
### Long-Term Maintainability
|
||||||
|
|
||||||
|
Markdown remains easy to review, while contracts remain stable for clients.
|
||||||
|
|
||||||
|
### Client Independence
|
||||||
|
|
||||||
|
Clients can use Ask, Edit, or Agent modes without requiring prompt-first orchestration. Prompt objects are available as an additive MCP surface, while resource retrieval remains the canonical source path. MCP affordances are still chat-surface-dependent: some clients or sessions expose resource attachment directly, while others make tool invocation the more reliable retrieval path.
|
||||||
|
|
||||||
|
## Authoring and Publishing Lifecycle
|
||||||
|
|
||||||
|
1. Update markdown reference content.
|
||||||
|
2. Update metadata if capability surface changes.
|
||||||
|
3. Build static docs with Zensical.
|
||||||
|
4. Serve built output through FastAPI static mount.
|
||||||
|
|
||||||
|
## Scope and Non-Goals
|
||||||
|
|
||||||
|
In-scope:
|
||||||
|
|
||||||
|
1. Resource-first methodology delivery
|
||||||
|
2. Catalog-based discovery
|
||||||
|
3. Pre-built static docs hosting in app runtime
|
||||||
|
|
||||||
|
Out-of-scope:
|
||||||
|
|
||||||
|
1. Prompt-first orchestration as the primary interface
|
||||||
|
2. Large tool inventories duplicating static guidance across skill modules
|
||||||
|
3. Separate dynamic docs service at runtime
|
||||||
|
|
||||||
|
Allowed exception:
|
||||||
|
|
||||||
|
1. A small catalog-level tool layer is acceptable when it improves client interoperability without creating a second source of truth for skill content.
|
||||||
|
|
||||||
|
## Example Content Inputs
|
||||||
|
|
||||||
|
Existing markdown reference sets are valid examples of authored source material for this architecture:
|
||||||
|
|
||||||
|
1. docs/skills/pytesting/references/pytest-docs.md
|
||||||
|
2. docs/skills/python-logging/references/python-logging-docs.md
|
||||||
|
3. docs/skills/python-logging/references/json-file-logging.md
|
||||||
|
4. docs/skills/fastapi-uv-docker/references/fastapi-best-practices.md
|
||||||
|
|
||||||
|
These inputs are treated as content sources, while resource URIs and catalog payloads remain the machine-facing contracts.
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/pencil
|
||||||
|
---
|
||||||
|
|
||||||
|
# Authoring Guide
|
||||||
|
|
||||||
|
This page defines the practical authoring workflow for this repository so Markdown remains the single source of truth for both published docs and MCP resources.
|
||||||
|
|
||||||
|
Primary references:
|
||||||
|
- [Skill contract](./contracts/skill_contract.md)
|
||||||
|
- [Prompt contract](./contracts/prompt.md)
|
||||||
|
- [Frontmatter contract](./contracts/frontmatter.md)
|
||||||
|
- [URI contract](./contracts/uris.md)
|
||||||
|
- [Zensical documentation authoring skill](./skills/zensical-docs/SKILL.md)
|
||||||
|
|
||||||
|
## What You Author
|
||||||
|
|
||||||
|
This repository has two primary authored content types:
|
||||||
|
|
||||||
|
1. Skills under `docs/skills/<skill-id>/`.
|
||||||
|
2. Prompts under `docs/prompts/<prompt-id>/`.
|
||||||
|
|
||||||
|
Each module keeps one canonical document plus optional references:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/
|
||||||
|
skills/<skill-id>/
|
||||||
|
SKILL.md
|
||||||
|
references/
|
||||||
|
*.md
|
||||||
|
|
||||||
|
prompts/<prompt-id>/
|
||||||
|
PROMPT.md
|
||||||
|
references/
|
||||||
|
*.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## Source Tree Ownership
|
||||||
|
|
||||||
|
Edit content only under the repository root `docs/` directory. The `src/personal_mcp/docs` path is a relative symlink provided so package-oriented tooling and editable installs see the same files; do not replace it with copied content or author files through a second tree.
|
||||||
|
|
||||||
|
[Hatchling forced inclusion](https://hatch.pypa.io/latest/config/build/#forced-inclusion) projects root `docs/` into `personal_mcp/docs/` when building the wheel. Installed code reads that destination through [`importlib.resources`](https://docs.python.org/3/library/importlib.resources.html), while Zensical continues to build the human-facing site directly from root `docs/`.
|
||||||
|
|
||||||
|
Package import does not load these resources. A runnable MCP or FastAPI server loads and validates them when its factory runs, then caches the immutable registry for that process. Restart initialized development or worker processes after changing authored Markdown.
|
||||||
|
|
||||||
|
## Authoring Principles
|
||||||
|
|
||||||
|
1. Keep Markdown as the canonical source and avoid duplicating content into alternate metadata files.
|
||||||
|
2. Prefer resource-first discovery paths (`resource://catalog/...` then `resource://skills/...` or `resource://prompts/...`).
|
||||||
|
3. Keep pages focused and composable: overview in the primary doc, details in `references/`.
|
||||||
|
4. Use descriptive inline links for external sources instead of bare URLs.
|
||||||
|
5. Use stable ids and slugs; renames are breaking changes and should be intentional.
|
||||||
|
|
||||||
|
## Skill Authoring Workflow
|
||||||
|
|
||||||
|
When creating or updating a skill:
|
||||||
|
|
||||||
|
1. Confirm slug format is lowercase kebab-case.
|
||||||
|
2. Keep directory name, `name`, and `x-personal-mcp.id` aligned.
|
||||||
|
3. Ensure capabilities include `resource://skills/<skill-id>/document`.
|
||||||
|
4. Place supporting material under `references/`.
|
||||||
|
5. Use explicit frontmatter reference entries only when you need overrides or nested mappings.
|
||||||
|
|
||||||
|
Recommended sequence:
|
||||||
|
|
||||||
|
1. Draft `SKILL.md` intent and routing sections.
|
||||||
|
2. Add or refine `references/*.md`.
|
||||||
|
3. Verify links and example commands.
|
||||||
|
4. Run docs build and tests.
|
||||||
|
|
||||||
|
For exact metadata rules, see [Frontmatter contract](./contracts/frontmatter.md) and [Skill contract](./contracts/skill_contract.md).
|
||||||
|
|
||||||
|
## Prompt Authoring Workflow
|
||||||
|
|
||||||
|
When creating or updating a prompt module:
|
||||||
|
|
||||||
|
1. Keep one canonical `PROMPT.md`.
|
||||||
|
2. Keep `name`, `x-personal-mcp.id`, and directory slug aligned.
|
||||||
|
3. Include `resource://prompts/<prompt-id>/document` in capabilities.
|
||||||
|
4. Define prompt arguments in `x-personal-mcp.arguments` when inputs are required.
|
||||||
|
5. Keep long rationale and source notes in `references/` to preserve prompt clarity.
|
||||||
|
|
||||||
|
For exact structure, see [Prompt contract](./contracts/prompt.md).
|
||||||
|
|
||||||
|
## Prompt Argument Mechanics
|
||||||
|
|
||||||
|
When defining prompt inputs, keep argument metadata aligned with the prompt contract and runtime behavior.
|
||||||
|
|
||||||
|
1. Define arguments under `x-personal-mcp.arguments` as a map keyed by argument name.
|
||||||
|
2. Argument names must match Python identifier format: `^[A-Za-z_][A-Za-z0-9_]*$`.
|
||||||
|
3. Each argument entry supports only:
|
||||||
|
- `title` (optional)
|
||||||
|
- `description` (optional)
|
||||||
|
- `required` (optional, defaults to `false`)
|
||||||
|
4. Unknown argument fields are rejected by strict frontmatter validation.
|
||||||
|
5. Prompt argument metadata appears in `resource://catalog/prompts/{prompt_id}`, and MCP prompt objects expose the same arguments for prompt-list/get-prompt workflows.
|
||||||
|
6. Enum-like constraints are not a native argument field; encode allowed values in `description`.
|
||||||
|
|
||||||
|
### Frontmatter Safety Rules
|
||||||
|
|
||||||
|
Use these rules to avoid YAML parse failures in prompt and skill frontmatter:
|
||||||
|
|
||||||
|
1. Quote any scalar value that contains `:` (for example, `description: "Enum: skill | prompt | shim"`).
|
||||||
|
2. Prefer quoted scalars for values with reserved YAML characters such as `#`, `{}`, `[]`, or leading `*`.
|
||||||
|
3. If a description needs multiple lines, use a block scalar (`|`) instead of packing punctuation-heavy text into one line.
|
||||||
|
4. Keep frontmatter keys simple and contract-bound; do not add undeclared argument fields.
|
||||||
|
|
||||||
|
### Validation Timing
|
||||||
|
|
||||||
|
Run validation immediately after frontmatter edits, not only at the end of a task:
|
||||||
|
|
||||||
|
1. First pass after metadata changes: `uv run zensical build`
|
||||||
|
2. Prompt/skill load verification: `uv run pytest -q`
|
||||||
|
3. Final full pass before completion: run the full checklist in [Validation Checklist](#validation-checklist)
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
x-personal-mcp:
|
||||||
|
arguments:
|
||||||
|
artifact_type:
|
||||||
|
title: Artifact type
|
||||||
|
description: Allowed values are skill, prompt, or shim.
|
||||||
|
required: true
|
||||||
|
scope_glob:
|
||||||
|
title: Scope glob
|
||||||
|
description: Optional applyTo glob for shim outputs.
|
||||||
|
required: false
|
||||||
|
```
|
||||||
|
|
||||||
|
References:
|
||||||
|
|
||||||
|
1. [Frontmatter contract](./contracts/frontmatter.md)
|
||||||
|
2. [URI contract](./contracts/uris.md)
|
||||||
|
3. [Resource-First Pattern Module Architecture](./architecture.md)
|
||||||
|
4. [Prompt objects concept docs](https://modelcontextprotocol.io/docs/learn/server-concepts#prompts)
|
||||||
|
|
||||||
|
## Writing Quality Rules
|
||||||
|
|
||||||
|
Apply these defaults to all docs pages:
|
||||||
|
|
||||||
|
1. Prefer short sections with strong headings over long unbroken prose.
|
||||||
|
2. Keep claims source-linked, especially for MCP, FastMCP, pytest, FastAPI, SQLAlchemy, and Zensical behavior.
|
||||||
|
3. Prefer relative links for internal docs paths.
|
||||||
|
4. Use code blocks for commands and configuration snippets.
|
||||||
|
5. Keep examples minimal and actionable.
|
||||||
|
|
||||||
|
Source examples:
|
||||||
|
- [Model Context Protocol docs](https://modelcontextprotocol.io/docs/getting-started/intro)
|
||||||
|
- [FastMCP docs](https://gofastmcp.com/getting-started/welcome)
|
||||||
|
- [Zensical docs](https://zensical.org/docs/)
|
||||||
|
|
||||||
|
## Authoring for GitHub Copilot
|
||||||
|
|
||||||
|
For resource selection or tool-based matching to work well, each skill should have:
|
||||||
|
|
||||||
|
1. precise `description`
|
||||||
|
2. focused `tags`
|
||||||
|
3. explicit `capabilities`
|
||||||
|
4. stable `id` and slug naming
|
||||||
|
|
||||||
|
Weak metadata reduces Copilot match quality and increases wrong context injection.
|
||||||
|
|
||||||
|
### Copilot Instruction Authoring Pattern
|
||||||
|
|
||||||
|
If you want Copilot to use `personal-mcp` skill content more reliably, instruction files should describe three things clearly:
|
||||||
|
|
||||||
|
1. when MCP-backed skill guidance is relevant
|
||||||
|
2. which retrieval path Copilot should prefer first
|
||||||
|
3. how much skill context it should load before answering
|
||||||
|
|
||||||
|
Instructions strongly steer discovery behavior, but they do not force VS Code to auto-attach MCP resources. Keep wording explicit about preferred path and fallback path.
|
||||||
|
|
||||||
|
Repository policy:
|
||||||
|
|
||||||
|
1. start from catalog discovery
|
||||||
|
2. prefer MCP resources when the current chat surface exposes resource attachment
|
||||||
|
3. fall back to catalog tools when resource attachment is unavailable
|
||||||
|
4. keep loaded skill context bounded
|
||||||
|
|
||||||
|
Suggested instruction text:
|
||||||
|
|
||||||
|
```md
|
||||||
|
When a task may match a documented implementation pattern from `personal-mcp`:
|
||||||
|
|
||||||
|
1. Start with catalog-first discovery.
|
||||||
|
2. Prefer MCP resources when the chat surface exposes resource attachment.
|
||||||
|
3. If MCP resource attachment is unavailable, use `list_resources`/`read_resource` first, then thin catalog tools if needed.
|
||||||
|
4. Load only the most relevant skill document, or at most 2 skill documents.
|
||||||
|
5. Reconcile loaded skill guidance with the actual repository code before making changes.
|
||||||
|
|
||||||
|
Preferred resource order:
|
||||||
|
|
||||||
|
1. `resource://catalog/skills_index`
|
||||||
|
2. `resource://catalog/skills/{skill_id}`
|
||||||
|
3. `resource://skills/<skill-id>/document`
|
||||||
|
4. `resource://skills/<skill-id>/references/<ref-id>` when needed
|
||||||
|
|
||||||
|
Preferred tool fallback order:
|
||||||
|
|
||||||
|
1. `list_resources`
|
||||||
|
2. `read_resource`
|
||||||
|
3. `search_patterns`
|
||||||
|
4. `get_pattern_by_id`
|
||||||
|
5. `get_skill_document_by_id`
|
||||||
|
|
||||||
|
Compatibility aliases for clients that use `catalog_*` naming are also available:
|
||||||
|
|
||||||
|
1. `catalog_search_patterns`
|
||||||
|
2. `catalog_get_pattern_by_id`
|
||||||
|
3. `catalog_get_skill_document_by_id`
|
||||||
|
4. `catalog_search_prompts`
|
||||||
|
5. `catalog_get_prompt_by_id`
|
||||||
|
|
||||||
|
Use canonical names first; aliases exist only to preserve interoperability when a client emits non-canonical names.
|
||||||
|
|
||||||
|
If confidence is low after discovery, ask one clarifying question before loading more context.
|
||||||
|
```
|
||||||
|
|
||||||
|
This is guidance, not a guarantee. It defines a reliable policy while preserving the resource-first architecture.
|
||||||
|
|
||||||
|
Thin shim path binding guidance for MCP consumers is covered in [Skill Usage Mechanics](./usage.md).
|
||||||
|
|
||||||
|
## Zensical Details
|
||||||
|
|
||||||
|
When adding or restructuring pages:
|
||||||
|
|
||||||
|
1. Update navigation in `zensical.toml`.
|
||||||
|
2. Ensure top-level pages include frontmatter with an icon.
|
||||||
|
3. Keep naming and labels concise so navigation remains scannable.
|
||||||
|
|
||||||
|
Top-level page pattern:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
icon: lucide/pencil
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
## Validation Checklist
|
||||||
|
|
||||||
|
Run these checks before considering authoring changes complete:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run zensical build
|
||||||
|
uv run ruff check .
|
||||||
|
uv run ty check
|
||||||
|
uv run pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
Address any errors or warnings that result.
|
||||||
|
|
||||||
|
If a change only affects docs content, `uv run zensical build` is still required.
|
||||||
|
|
||||||
|
## Quick Authoring Checklist
|
||||||
|
|
||||||
|
1. Correct location (`skills/` or `prompts/`).
|
||||||
|
2. Frontmatter id and slug alignment.
|
||||||
|
3. Capability URI present.
|
||||||
|
4. Links valid and descriptive.
|
||||||
|
5. Navigation updated when needed.
|
||||||
|
6. Validation commands passed.
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/braces
|
||||||
|
---
|
||||||
|
|
||||||
|
# Frontmatter Contract
|
||||||
|
|
||||||
|
This page defines the `SKILL.md` frontmatter and FastMCP metadata contract.
|
||||||
|
|
||||||
|
Prompt modules use the same contract style in `docs/prompts/<prompt-id>/PROMPT.md` with prompt-specific capability and MCP-aligned prompt argument metadata.
|
||||||
|
|
||||||
|
## Validated Frontmatter Surface
|
||||||
|
|
||||||
|
The registry runtime validates a strict, standard-only frontmatter surface:
|
||||||
|
|
||||||
|
1. Top-level fields accepted for skills: `name`, `description`, `x-personal-mcp`.
|
||||||
|
2. Top-level fields accepted for prompts: `name`, `description`, `x-personal-mcp`.
|
||||||
|
3. Unknown top-level fields are rejected during registry load.
|
||||||
|
|
||||||
|
Skill and prompt identifier rules:
|
||||||
|
|
||||||
|
1. `name` is required, 1-64 chars, lowercase kebab-case, and must not contain `anthropic` or `claude`.
|
||||||
|
2. `description` is required, 1-1024 chars.
|
||||||
|
3. `x-personal-mcp.id` must exactly match `name`.
|
||||||
|
4. Directory slug must exactly match `name`.
|
||||||
|
|
||||||
|
Capability invariants:
|
||||||
|
|
||||||
|
1. Skill capabilities must include `resource://skills/<skill-id>/document`.
|
||||||
|
2. Prompt capabilities must include `resource://prompts/<prompt-id>/document`.
|
||||||
|
|
||||||
|
Repository contract decisions:
|
||||||
|
|
||||||
|
1. Treat `name` and `description` as required in all `SKILL.md` files.
|
||||||
|
2. Keep only validated standard fields at top level.
|
||||||
|
3. Keep MCP indexing metadata in a namespaced extension block.
|
||||||
|
4. Reject unsupported optional top-level fields until explicit model support is added.
|
||||||
|
|
||||||
|
Reference specs:
|
||||||
|
|
||||||
|
1. MCP prompts data types: [Prompts](https://modelcontextprotocol.io/specification/latest/server/prompts)
|
||||||
|
2. MCP schema reference for `Prompt` and `PromptArgument`: [Schema](https://modelcontextprotocol.io/specification/latest/schema)
|
||||||
|
|
||||||
|
## Canonical Frontmatter Schema
|
||||||
|
|
||||||
|
Use this two-layer pattern:
|
||||||
|
|
||||||
|
1. Anthropic layer: top-level fields intended for Anthropic and Agent Skills behavior.
|
||||||
|
2. Repository layer: one namespaced block, `x-personal-mcp`, for MCP catalog and routing metadata.
|
||||||
|
|
||||||
|
Canonical shape:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
name: <skill-id>
|
||||||
|
description: <what this skill does and when to use it>
|
||||||
|
|
||||||
|
# Repository-specific metadata
|
||||||
|
x-personal-mcp:
|
||||||
|
id: <skill-id>
|
||||||
|
version: <semver>
|
||||||
|
tags:
|
||||||
|
- <tag>
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/<skill-id>/document
|
||||||
|
# Optional: overrides and nested references only.
|
||||||
|
# Top-level references/*.md are auto-discovered.
|
||||||
|
references:
|
||||||
|
<ref-id>:
|
||||||
|
path: references/<file>.md
|
||||||
|
mime_type: text/markdown
|
||||||
|
title: <short title>
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
## Repository Metadata Field Rules
|
||||||
|
|
||||||
|
Rules for `x-personal-mcp`:
|
||||||
|
|
||||||
|
1. `id` is required, must follow the skill id rules from the content contract, and must equal the directory name.
|
||||||
|
2. `version` is required and must be a semantic version string.
|
||||||
|
3. `tags` is optional and should be a list of kebab-case discovery labels.
|
||||||
|
4. `capabilities` is required and lists the MCP URIs the skill publishes.
|
||||||
|
5. `references` is an optional map keyed by `ref-id` for overrides and nested entries.
|
||||||
|
|
||||||
|
Prompt-specific additions:
|
||||||
|
|
||||||
|
1. `arguments` is an optional map keyed by argument name.
|
||||||
|
2. Each argument supports optional `title`, optional `description`, and optional `required`.
|
||||||
|
3. This aligns with MCP `PromptArgument` shape (`name`, optional `title`, optional `description`, optional `required`) where `name` is represented by the map key.
|
||||||
|
4. Prompt `capabilities` must include `resource://prompts/<prompt-id>/document`.
|
||||||
|
|
||||||
|
Example prompt frontmatter:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
name: initial-test-structure
|
||||||
|
description: Generate a baseline pytest test layout for a target scope.
|
||||||
|
x-personal-mcp:
|
||||||
|
id: initial-test-structure
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- pytest
|
||||||
|
- testing
|
||||||
|
capabilities:
|
||||||
|
- resource://prompts/initial-test-structure/document
|
||||||
|
arguments:
|
||||||
|
target_scope:
|
||||||
|
title: Target scope
|
||||||
|
description: Target package or module under test.
|
||||||
|
required: true
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference entry rules:
|
||||||
|
|
||||||
|
1. `ref-id` is lowercase kebab-case.
|
||||||
|
2. `path` is a skill-relative markdown path and must stay inside the same skill directory.
|
||||||
|
3. Top-level files under `references/*.md` are auto-discovered with `ref-id` derived from a normalized filename stem (lowercase kebab-case).
|
||||||
|
4. Nested folders under `references/` are not auto-discovered and must be declared explicitly.
|
||||||
|
5. `mime_type` defaults to `text/markdown` when omitted.
|
||||||
|
6. `title` is an optional display label.
|
||||||
|
7. Renaming `ref-id` values is allowed when needed; optional aliases may be used during transitions.
|
||||||
|
|
||||||
|
## Auto-Generated Reference IDs
|
||||||
|
|
||||||
|
Top-level markdown files directly under `references/` are auto-registered as MCP references even when `x-personal-mcp.references` is empty.
|
||||||
|
|
||||||
|
How `ref-id` is derived:
|
||||||
|
|
||||||
|
1. Start from the filename stem (without `.md`).
|
||||||
|
2. Normalize to lowercase kebab-case.
|
||||||
|
3. Publish at `resource://skills/<skill-id>/references/<ref-id>`.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
1. `references/ruff-docs.md` -> `ref-id: ruff-docs`
|
||||||
|
2. `references/Ruff Integrations.md` -> `ref-id: ruff-integrations`
|
||||||
|
3. `references/python_logging_docs.md` -> `ref-id: python-logging-docs`
|
||||||
|
|
||||||
|
When to use explicit `x-personal-mcp.references` entries:
|
||||||
|
|
||||||
|
1. The file is nested, for example `references/guides/ci.md`.
|
||||||
|
2. You need to override defaults (`title`, `mime_type`, or custom `ref-id`).
|
||||||
|
3. You need compatibility aliases during a rename.
|
||||||
|
|
||||||
|
## Validation Models
|
||||||
|
|
||||||
|
The normative runtime model uses strict Pydantic v2 validation:
|
||||||
|
|
||||||
|
1. Models are immutable (`frozen=True`) and reject unknown fields (`extra="forbid"`).
|
||||||
|
2. `SkillFrontmatter` accepts only `name`, `description`, and `x-personal-mcp`.
|
||||||
|
3. `PromptFrontmatter` accepts only `name`, `description`, and `x-personal-mcp`.
|
||||||
|
4. `PromptArgumentEntry` accepts only optional `title`, optional `description`, and optional `required`.
|
||||||
|
5. Skill and prompt metadata enforce semver, kebab-case ids, capability requirements, and id/name/directory consistency.
|
||||||
|
6. Reference paths are validated as markdown files under `references/`.
|
||||||
|
|
||||||
|
Validation behavior contract:
|
||||||
|
|
||||||
|
1. Validate required core fields and relationships during registry load before FastMCP resource or tool registration.
|
||||||
|
2. Reject unknown or unsupported fields at parse and model-validation time.
|
||||||
|
3. Treat hard contract violations, including missing required fields, invalid ids, and broken required mappings, as startup errors.
|
||||||
|
4. Keep failure messages path-aware and field-specific for CI readability.
|
||||||
|
|
||||||
|
Projection mode contract for Anthropic API upload pipelines:
|
||||||
|
|
||||||
|
1. Parse with `SkillFrontmatter` first.
|
||||||
|
2. Emit Anthropic-safe frontmatter with standard fields only.
|
||||||
|
3. Preserve `x-personal-mcp` in source-of-truth documents; projection output is a build artifact.
|
||||||
|
|
||||||
|
## Anthropic Upload Compatibility Rule
|
||||||
|
|
||||||
|
1. Anthropic documentation guarantees behavior for standard frontmatter fields but does not explicitly guarantee handling of arbitrary unknown top-level keys.
|
||||||
|
2. Publishing pipelines that target strict API compatibility should support a projection mode that emits only standard frontmatter fields for upload.
|
||||||
|
3. Source-of-truth authoring remains in `x-personal-mcp`; upload payload shape is an explicit build concern.
|
||||||
|
|
||||||
|
## FastMCP Native Metadata Surfaces
|
||||||
|
|
||||||
|
Resources support native definition metadata:
|
||||||
|
|
||||||
|
1. `name`
|
||||||
|
2. `description`
|
||||||
|
3. `mime_type`
|
||||||
|
4. `tags`
|
||||||
|
5. `annotations`, including `readOnlyHint` and `idempotentHint`
|
||||||
|
6. `icons`
|
||||||
|
7. `meta`
|
||||||
|
8. `version`
|
||||||
|
9. `enabled`, which is deprecated in FastMCP v3 in favor of server-level enable and disable controls
|
||||||
|
|
||||||
|
Resources also support runtime metadata through `ResourceContent.meta` and `ResourceResult.meta`.
|
||||||
|
|
||||||
|
Tools support native definition metadata:
|
||||||
|
|
||||||
|
1. `name`
|
||||||
|
2. `description`
|
||||||
|
3. `tags`
|
||||||
|
4. `annotations`, including `title`, `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint`
|
||||||
|
5. `icons`
|
||||||
|
6. `meta`
|
||||||
|
7. `version`
|
||||||
|
8. `timeout`
|
||||||
|
9. `output_schema`
|
||||||
|
10. `run_in_thread`
|
||||||
|
11. `enabled`, which is deprecated in FastMCP v3 in favor of server-level enable and disable controls
|
||||||
|
|
||||||
|
Tools also support runtime metadata through `ToolResult.meta`.
|
||||||
|
|
||||||
|
## Frontmatter To FastMCP Mapping Contract
|
||||||
|
|
||||||
|
At server startup, map `x-personal-mcp` into FastMCP registration as follows:
|
||||||
|
|
||||||
|
1. `x-personal-mcp.id` defines the canonical URI namespace and identity checks.
|
||||||
|
2. `description` becomes the default description for the primary skill document resource.
|
||||||
|
3. `x-personal-mcp.tags` maps to resource and tool tags.
|
||||||
|
4. `x-personal-mcp.version` maps to resource and tool version metadata.
|
||||||
|
5. `x-personal-mcp.capabilities` becomes the registered URI list and catalog exposure.
|
||||||
|
6. `x-personal-mcp.references[*]` becomes resource templates or concrete resources with `mime_type`, read-only annotations, and `meta` that includes `skill_id`, `ref_id`, and source `path`.
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
This contract guarantees:
|
||||||
|
|
||||||
|
1. Anthropic-required frontmatter stays valid for custom skill upload and Claude Code loading.
|
||||||
|
2. MCP-specific metadata remains embedded in `SKILL.md` frontmatter, with no `metadata.yaml` sidecar.
|
||||||
|
3. FastMCP registration uses native metadata fields for resources and tools.
|
||||||
|
4. Reference ids and metadata can evolve with low-friction updates while internal file layout under `references/` stays refactor-friendly.
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
This contract does not define:
|
||||||
|
|
||||||
|
1. URI versioning and deprecation rollout policy details.
|
||||||
|
2. Migration script design from existing `metadata.yaml` files.
|
||||||
|
3. Runtime caching and indexing performance tuning.
|
||||||
@@ -21,13 +21,13 @@ This page defines the authored content contract for the docs-first MCP architect
|
|||||||
|
|
||||||
## Canonical Source Of Truth
|
## Canonical Source Of Truth
|
||||||
|
|
||||||
1. All authored Markdown lives under `src/personal_mcp/docs/`.
|
1. All authored Markdown lives under `docs/`.
|
||||||
2. MCP resources and static docs are two distribution surfaces of the same authored files.
|
2. MCP resources and static docs are two distribution surfaces of the same authored files.
|
||||||
3. No parallel authored Markdown is allowed in a root `docs/` directory or another source tree.
|
3. No parallel authored markdown is allowed in `src/` or other package-only paths.
|
||||||
|
|
||||||
## Canonical Content Shape
|
## Canonical Content Shape
|
||||||
|
|
||||||
Authored content is organized under `src/personal_mcp/docs/`:
|
Authored content is organized under `docs/`:
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
---
|
---
|
||||||
@@ -41,7 +41,7 @@ config:
|
|||||||
lineColor: '#FFFFFF'
|
lineColor: '#FFFFFF'
|
||||||
---
|
---
|
||||||
treeView-beta
|
treeView-beta
|
||||||
"src/personal_mcp/docs/"
|
"docs/"
|
||||||
"*.md (top-level docs pages)"
|
"*.md (top-level docs pages)"
|
||||||
"contracts/"
|
"contracts/"
|
||||||
"prompt.md"
|
"prompt.md"
|
||||||
@@ -59,9 +59,9 @@ treeView-beta
|
|||||||
|
|
||||||
## File Placement And Ownership Boundaries
|
## File Placement And Ownership Boundaries
|
||||||
|
|
||||||
1. Top-level project docs stay in `src/personal_mcp/docs/*.md`.
|
1. Top-level project docs stay in `docs/*.md`.
|
||||||
2. Skill docs stay in `src/personal_mcp/docs/skills/<skill-id>/...`.
|
2. Skill docs stay in `docs/skills/<skill-id>/...`.
|
||||||
3. Prompt docs stay in `src/personal_mcp/docs/prompts/<prompt-id>/...`.
|
3. Prompt docs stay in `docs/prompts/<prompt-id>/...`.
|
||||||
4. A skill or prompt may link across sections, but must not store content in another artifact's directory.
|
4. A skill or prompt may link across sections, but must not store content in another artifact's directory.
|
||||||
5. Server and runtime code may index and serve docs, but must not be the source of authored markdown.
|
5. Server and runtime code may index and serve docs, but must not be the source of authored markdown.
|
||||||
|
|
||||||
@@ -74,7 +74,7 @@ treeView-beta
|
|||||||
|
|
||||||
This contract guarantees:
|
This contract guarantees:
|
||||||
|
|
||||||
1. One authored source tree in `src/personal_mcp/docs/` for both website and MCP.
|
1. One authored source tree in `docs/` for both website and MCP.
|
||||||
2. Skill and prompt artifacts remain path-stable within their own sections.
|
2. Skill and prompt artifacts remain path-stable within their own sections.
|
||||||
3. Cross-surface publishing remains deterministic because authored content paths are canonical.
|
3. Cross-surface publishing remains deterministic because authored content paths are canonical.
|
||||||
|
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/messages-square
|
||||||
|
---
|
||||||
|
|
||||||
|
# Prompt Contract
|
||||||
|
|
||||||
|
This page defines the canonical contract for prompts in the docs-first MCP architecture.
|
||||||
|
|
||||||
|
## Canonical Prompt Shape
|
||||||
|
|
||||||
|
Each prompt is one directory under `docs/prompts/`:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
---
|
||||||
|
config:
|
||||||
|
treeView:
|
||||||
|
rowIndent: 20
|
||||||
|
lineThickness: 2
|
||||||
|
themeVariables:
|
||||||
|
treeView:
|
||||||
|
labelColor: '#FFFFFF'
|
||||||
|
lineColor: '#FFFFFF'
|
||||||
|
---
|
||||||
|
treeView-beta
|
||||||
|
"docs/"
|
||||||
|
"... (other docs)"
|
||||||
|
"prompts/"
|
||||||
|
"<prompt-id>/"
|
||||||
|
"PROMPT.md"
|
||||||
|
"references/"
|
||||||
|
"... (one or more markdown files, optional nested folders)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. `PROMPT.md` is required for every prompt.
|
||||||
|
2. `references/` is the only place for prompt-specific supporting docs.
|
||||||
|
3. Nested folders inside `references/` are allowed so a prompt can reorganize internals without changing global architecture.
|
||||||
|
4. Prompt directories are independent ownership boundaries; no cross-prompt file writes.
|
||||||
|
|
||||||
|
## Metadata Location Constraint
|
||||||
|
|
||||||
|
1. Prompt metadata is embedded in YAML frontmatter in `PROMPT.md`.
|
||||||
|
2. No `metadata.yaml` sidecar exists in the end state.
|
||||||
|
3. Reference lookup metadata is documented and explicit: top-level `references/*.md` are auto-discovered from filenames, while `PROMPT.md` frontmatter declares overrides and nested mappings when needed.
|
||||||
|
|
||||||
|
## Prompt Id Contract
|
||||||
|
|
||||||
|
`prompt-id` is the public identifier and should satisfy all rules below:
|
||||||
|
|
||||||
|
1. Format: lowercase kebab-case only.
|
||||||
|
2. Character set: `a-z`, `0-9`, and `-`.
|
||||||
|
3. Must start with a letter.
|
||||||
|
4. No underscores, spaces, dots, or uppercase characters.
|
||||||
|
5. Directory name should equal `prompt-id` in each committed revision.
|
||||||
|
6. Frontmatter `id` should equal directory name in each committed revision.
|
||||||
|
7. Treat `prompt-id` as immutable after release; any rename is a breaking replacement and clients must move to the new id.
|
||||||
|
|
||||||
|
Valid examples:
|
||||||
|
|
||||||
|
1. `pytest-fill-scaffold`
|
||||||
|
2. `review-pr-comments`
|
||||||
|
3. `scaffold-fastapi-service`
|
||||||
|
|
||||||
|
Invalid examples:
|
||||||
|
|
||||||
|
1. `fill_pytest_scaffold`
|
||||||
|
2. `Prompt-Template`
|
||||||
|
3. `docs.prompt`
|
||||||
|
|
||||||
|
## Direct Documentation Inclusion
|
||||||
|
|
||||||
|
1. For direct API documentation, use mkdocstrings directives rather than pasting large code blocks.
|
||||||
|
2. Keep manually-authored code examples short and task-focused; large implementation excerpts are out of scope for this contract.
|
||||||
|
|
||||||
+7
-17
@@ -8,7 +8,7 @@ This page defines the canonical contract for skills in the docs-first MCP archit
|
|||||||
|
|
||||||
## Canonical Skill Shape
|
## Canonical Skill Shape
|
||||||
|
|
||||||
Each skill is one directory under `src/personal_mcp/docs/skills/`:
|
Each skill is one directory under `docs/skills/`:
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
---
|
---
|
||||||
@@ -22,7 +22,7 @@ config:
|
|||||||
lineColor: '#FFFFFF'
|
lineColor: '#FFFFFF'
|
||||||
---
|
---
|
||||||
treeView-beta
|
treeView-beta
|
||||||
"src/personal_mcp/docs/"
|
"docs/"
|
||||||
"... (other docs)"
|
"... (other docs)"
|
||||||
"skills/"
|
"skills/"
|
||||||
"<skill-id>/"
|
"<skill-id>/"
|
||||||
@@ -40,9 +40,9 @@ Rules:
|
|||||||
|
|
||||||
## Metadata Location Constraint
|
## Metadata Location Constraint
|
||||||
|
|
||||||
1. `SKILL.md` frontmatter contains only standard `name` and `description` fields.
|
1. Skill metadata is embedded in YAML frontmatter in `SKILL.md`.
|
||||||
2. No `metadata.yaml` sidecar or repository-specific skill metadata block exists.
|
2. No `metadata.yaml` sidecar exists in the end state.
|
||||||
3. The provider discovers supporting files recursively; their real relative paths are published in the generated `_manifest`.
|
3. Reference lookup metadata is documented and explicit: top-level `references/*.md` are auto-discovered from filenames, while `SKILL.md` frontmatter declares overrides and nested mappings when needed.
|
||||||
|
|
||||||
## Skill Id Contract
|
## Skill Id Contract
|
||||||
|
|
||||||
@@ -52,8 +52,8 @@ Rules:
|
|||||||
2. Character set: `a-z`, `0-9`, and `-`.
|
2. Character set: `a-z`, `0-9`, and `-`.
|
||||||
3. Must start with a letter.
|
3. Must start with a letter.
|
||||||
4. No underscores, spaces, dots, or uppercase characters.
|
4. No underscores, spaces, dots, or uppercase characters.
|
||||||
5. Directory name equals `skill-id` in each committed revision.
|
5. Directory name should equal `skill-id` in each committed revision.
|
||||||
6. Frontmatter `name` equals the directory name.
|
6. Frontmatter `id` should equal directory name in each committed revision.
|
||||||
7. Treat `skill-id` as immutable after release; any rename is a breaking replacement and clients must move to the new id.
|
7. Treat `skill-id` as immutable after release; any rename is a breaking replacement and clients must move to the new id.
|
||||||
|
|
||||||
Valid examples:
|
Valid examples:
|
||||||
@@ -68,16 +68,6 @@ Invalid examples:
|
|||||||
2. `Zensical-Docs`
|
2. `Zensical-Docs`
|
||||||
3. `docs.zensical`
|
3. `docs.zensical`
|
||||||
|
|
||||||
## Provider Publication
|
|
||||||
|
|
||||||
[`SkillsDirectoryProvider`](https://gofastmcp.com/servers/providers/skills) scans packaged `personal_mcp/docs/skills/` with `supporting_files="template"` and publishes:
|
|
||||||
|
|
||||||
1. `skill://<skill-id>/SKILL.md`
|
|
||||||
2. `skill://<skill-id>/_manifest`
|
|
||||||
3. `skill://<skill-id>/{path*}` for supporting files
|
|
||||||
|
|
||||||
Only the main file and manifest appear in `resources/list`. Clients inspect the manifest before reading supporting paths.
|
|
||||||
|
|
||||||
## Direct Documentation Inclusion
|
## Direct Documentation Inclusion
|
||||||
|
|
||||||
1. For direct API documentation, use mkdocstrings directives rather than pasting large code blocks.
|
1. For direct API documentation, use mkdocstrings directives rather than pasting large code blocks.
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/link
|
||||||
|
---
|
||||||
|
|
||||||
|
# URI Contract
|
||||||
|
|
||||||
|
This page defines the canonical resource URI contract, template parameter rules, and compatibility policy.
|
||||||
|
|
||||||
|
Conventions in this document follow [MCP resource semantics](https://modelcontextprotocol.io/docs/learn/server-concepts#resources), [URI generic syntax (RFC3986)](https://www.rfc-editor.org/rfc/rfc3986), and [URI templates (RFC6570)](https://www.rfc-editor.org/rfc/rfc6570).
|
||||||
|
|
||||||
|
## Canonical URI Surface
|
||||||
|
|
||||||
|
The public, preferred direct resource URIs are:
|
||||||
|
|
||||||
|
1. `resource://catalog/skills_index`
|
||||||
|
2. `resource://catalog/skills/{skill_id}`
|
||||||
|
3. `resource://skills/{skill_id}/document`
|
||||||
|
4. `resource://skills/{skill_id}/references/{ref_id}`
|
||||||
|
5. `resource://docs/{path*}`
|
||||||
|
6. `resource://catalog/prompts_index`
|
||||||
|
7. `resource://catalog/prompts/{prompt_id}`
|
||||||
|
8. `resource://prompts/{prompt_id}/document`
|
||||||
|
|
||||||
|
The public, preferred resource template URIs are:
|
||||||
|
|
||||||
|
1. `resource://catalog/skills_index{?q,tag,capability,cursor,limit}`
|
||||||
|
2. `resource://catalog/prompts_index{?q,tag,cursor,limit}`
|
||||||
|
|
||||||
|
Contract intent:
|
||||||
|
|
||||||
|
1. Catalog URIs are discovery surfaces.
|
||||||
|
2. Skill URIs are the primary per-skill guidance surfaces.
|
||||||
|
3. Catalog query templates are additive discovery helpers for filtering and pagination.
|
||||||
|
4. The docs wildcard URI is a direct authored-markdown access surface under `docs/`.
|
||||||
|
|
||||||
|
Best-practice alignment:
|
||||||
|
|
||||||
|
1. Resource identifiers are stable and noun-oriented.
|
||||||
|
2. Dynamic lookup variants are represented as RFC6570 templates.
|
||||||
|
3. Resources remain read-oriented and are described with explicit MIME types.
|
||||||
|
|
||||||
|
## URI Semantics
|
||||||
|
|
||||||
|
### `resource://catalog/skills_index`
|
||||||
|
|
||||||
|
1. Returns a compact list of skill records for discovery.
|
||||||
|
2. Contains one entry per `skill_id`.
|
||||||
|
3. Includes enough metadata for client-side selection, at minimum `id`, `name`, `description`, `tags`, and `capabilities`.
|
||||||
|
|
||||||
|
### `resource://catalog/skills/{skill_id}`
|
||||||
|
|
||||||
|
1. Returns one normalized record for `skill_id`.
|
||||||
|
2. Includes the canonical document URI and declared reference ids.
|
||||||
|
3. Returns not found when `skill_id` does not exist.
|
||||||
|
|
||||||
|
### `resource://skills/{skill_id}/document`
|
||||||
|
|
||||||
|
1. Returns the canonical `SKILL.md` authored content for that skill.
|
||||||
|
2. `skill_id` must satisfy the stable skill id rules from the content contract.
|
||||||
|
|
||||||
|
### `resource://skills/{skill_id}/references/{ref_id}`
|
||||||
|
|
||||||
|
1. Returns one reference document declared in the skill frontmatter references manifest.
|
||||||
|
2. `ref_id` is the stable public handle for that reference document.
|
||||||
|
|
||||||
|
### `resource://docs/{path*}`
|
||||||
|
|
||||||
|
1. Returns authored markdown at a normalized relative path under `docs/`.
|
||||||
|
2. Supports nested paths via [RFC6570 wildcard expansion](https://www.rfc-editor.org/rfc/rfc6570).
|
||||||
|
3. Typical examples include `index.md`, `usage.md`, `skills/<skill-id>/SKILL.md`, and `skills/<skill-id>/references/<file>.md`.
|
||||||
|
|
||||||
|
### `resource://catalog/prompts_index`
|
||||||
|
|
||||||
|
1. Returns a compact list of prompt records for discovery.
|
||||||
|
2. Contains one entry per `prompt_id`.
|
||||||
|
3. Includes `id`, `name`, `description`, `tags`, `version`, and canonical document URI.
|
||||||
|
|
||||||
|
### `resource://catalog/skills_index{?q,tag,capability,cursor,limit}`
|
||||||
|
|
||||||
|
1. Returns the same record family as `resource://catalog/skills_index` with optional filtering and pagination.
|
||||||
|
2. Query parameters are optional and composable.
|
||||||
|
3. Unknown query keys are ignored or rejected deterministically by server policy.
|
||||||
|
|
||||||
|
### `resource://catalog/prompts_index{?q,tag,cursor,limit}`
|
||||||
|
|
||||||
|
1. Returns the same record family as `resource://catalog/prompts_index` with optional filtering and pagination.
|
||||||
|
2. Query parameters are optional and composable.
|
||||||
|
3. Unknown query keys are ignored or rejected deterministically by server policy.
|
||||||
|
|
||||||
|
### `resource://catalog/prompts/{prompt_id}`
|
||||||
|
|
||||||
|
1. Returns one normalized record for `prompt_id`.
|
||||||
|
2. Includes prompt argument metadata when declared in frontmatter.
|
||||||
|
3. Returns not found when `prompt_id` does not exist.
|
||||||
|
|
||||||
|
### `resource://prompts/{prompt_id}/document`
|
||||||
|
|
||||||
|
1. Returns the canonical prompt markdown document.
|
||||||
|
2. `prompt_id` must satisfy lowercase kebab-case rules.
|
||||||
|
|
||||||
|
## Template Parameter And Validation Rules
|
||||||
|
|
||||||
|
### `skill_id`
|
||||||
|
|
||||||
|
1. Lowercase kebab-case.
|
||||||
|
2. Must satisfy the stable skill id rules from the content contract.
|
||||||
|
|
||||||
|
### `ref_id`
|
||||||
|
|
||||||
|
1. Lowercase kebab-case.
|
||||||
|
2. Must be declared in the skill's references manifest.
|
||||||
|
|
||||||
|
### `path*`
|
||||||
|
|
||||||
|
1. Relative POSIX path only, expressed as URI path segments under [RFC3986 path syntax](https://www.rfc-editor.org/rfc/rfc3986#section-3.3).
|
||||||
|
2. No leading slash.
|
||||||
|
3. No `..` traversal segments.
|
||||||
|
4. Resolves only inside `docs/`.
|
||||||
|
5. Markdown-only in the end state, meaning `.md` files.
|
||||||
|
6. Any reserved URI characters in path segments must be [percent-encoded](https://www.rfc-editor.org/rfc/rfc3986#section-2.1).
|
||||||
|
|
||||||
|
### `prompt_id`
|
||||||
|
|
||||||
|
1. Lowercase kebab-case.
|
||||||
|
2. Must be unique across prompt ids and must not collide with skill ids.
|
||||||
|
|
||||||
|
## URI Hygiene Rules
|
||||||
|
|
||||||
|
1. Use lowercase, human-readable path segments for stable discoverability.
|
||||||
|
2. Keep identifiers immutable once public whenever practical.
|
||||||
|
3. Keep template variables semantic (`skill_id`, `prompt_id`, `ref_id`, `path*`) and avoid overloading one variable for unrelated meanings.
|
||||||
|
4. Do not include secrets, tokens, or user-identifying data in URI paths or query strings.
|
||||||
|
5. Prefer additive query parameters for discovery over introducing parallel URI families, matching [MCP resource-template discovery patterns](https://modelcontextprotocol.io/docs/learn/server-concepts#resources).
|
||||||
|
6. Return clear not-found semantics for unknown ids and invalid template resolution.
|
||||||
|
|
||||||
|
## URI Versioning Policy
|
||||||
|
|
||||||
|
Default rule:
|
||||||
|
|
||||||
|
1. Keep URIs unversioned by default.
|
||||||
|
2. Allow URI and payload updates when they improve clarity or implementation simplicity.
|
||||||
|
|
||||||
|
Breaking-change rule:
|
||||||
|
|
||||||
|
1. Breaking changes use direct replacement of the canonical URI family.
|
||||||
|
2. No compatibility aliases or dual URI families are maintained.
|
||||||
|
|
||||||
|
FastMCP version metadata usage:
|
||||||
|
|
||||||
|
1. Resource `version` metadata may be used for implementation and version discovery.
|
||||||
|
2. URI readability and maintainability remain the primary contract.
|
||||||
|
|
||||||
|
## Reference Id Compatibility Policy
|
||||||
|
|
||||||
|
`ref_id` is the public identifier for a reference document, separate from file path.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. Prefer keeping `ref_id` stable when practical.
|
||||||
|
2. File paths may change without URI churn as long as the mapped `ref_id` still resolves.
|
||||||
|
3. If a reference is renamed, introduce a new `ref_id` and treat the old one as retired.
|
||||||
|
4. Avoid reusing retired `ref_id` values for unrelated content.
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
This contract guarantees:
|
||||||
|
|
||||||
|
1. One canonical URI pattern per core capability surface.
|
||||||
|
2. Fast, low-friction URI evolution through direct replacement of canonical URIs.
|
||||||
|
3. A single canonical catalog URI family with no alias maintenance overhead.
|
||||||
|
4. Reference mappings can evolve with minimal churn.
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
This contract does not define:
|
||||||
|
|
||||||
|
1. Implementation-specific transform wiring details, such as `VersionFilter`, mounts, or provider composition.
|
||||||
|
2. Migration script mechanics for auto-generating aliases.
|
||||||
|
3. Authorization policy design for URI-level access control.
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
1. [MCP Server Concepts: Resources](https://modelcontextprotocol.io/docs/learn/server-concepts#resources)
|
||||||
|
2. [MCP Architecture Overview](https://modelcontextprotocol.io/docs/learn/architecture)
|
||||||
|
3. [MCP Specification Repository](https://github.com/modelcontextprotocol/spec)
|
||||||
|
4. [RFC6570 URI Template](https://www.rfc-editor.org/rfc/rfc6570)
|
||||||
+204
@@ -0,0 +1,204 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/bot
|
||||||
|
---
|
||||||
|
|
||||||
|
# Copilot MCP Mechanics
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This page explains how the GitHub Copilot extension in VS Code behaves as an MCP client when connected to `personal-mcp`, including why tools can appear while resource attachment appears unavailable.
|
||||||
|
|
||||||
|
## Core Model
|
||||||
|
|
||||||
|
Copilot interacts with MCP servers through separate capability lanes:
|
||||||
|
|
||||||
|
1. tools (invoked by the model during execution)
|
||||||
|
2. resources (attached as read-only context)
|
||||||
|
3. prompts (server-provided prompt templates)
|
||||||
|
|
||||||
|
These lanes are related but independently gated in the client.
|
||||||
|
|
||||||
|
Reliable paths are:
|
||||||
|
|
||||||
|
1. attach MCP resources explicitly through `Add Context > MCP Resources` or `MCP: Browse Resources`
|
||||||
|
2. let Copilot invoke MCP tools when the task and tool descriptions make that relevant
|
||||||
|
3. invoke MCP prompts explicitly with `/server.prompt` when your server exposes them
|
||||||
|
|
||||||
|
## What Actually Happens In VS Code
|
||||||
|
|
||||||
|
### MCP server side
|
||||||
|
|
||||||
|
Your server can advertise resources and serve them correctly. In this project that includes catalog resources and skill document resources.
|
||||||
|
|
||||||
|
### Copilot session side
|
||||||
|
|
||||||
|
The chat surface exposes tools, resources, and prompts through different UI paths. In practice, you can encounter sessions where tool use is available but MCP resource attachment is not exposed in `Add Context`.
|
||||||
|
|
||||||
|
That is why you can sometimes see MCP tools before you see `Add Context > MCP Resources`.
|
||||||
|
|
||||||
|
## Why The Picker Sometimes Shows Only Tools
|
||||||
|
|
||||||
|
`MCP Resources...` in Add Context requires at least:
|
||||||
|
|
||||||
|
1. at least one connected MCP server advertises resource capability
|
||||||
|
2. the current chat surface exposes MCP resource attachment
|
||||||
|
|
||||||
|
If the second condition is not met, resources can be available on the server while still being absent from the picker.
|
||||||
|
|
||||||
|
## Practical Workflow
|
||||||
|
|
||||||
|
Use this sequence to confirm behavior:
|
||||||
|
|
||||||
|
1. run `MCP: Browse Resources` and verify resources exist
|
||||||
|
2. use `MCP: List Servers` to verify the server is enabled and running
|
||||||
|
3. open Copilot Chat
|
||||||
|
4. check `Add Context` for `MCP Resources...`
|
||||||
|
5. if still missing, restart the server and reload VS Code window
|
||||||
|
|
||||||
|
## Recommended Usage Pattern
|
||||||
|
|
||||||
|
1. rely on canonical catalog resources for discovery (`skills_index`, then `skills/{skill_id}`)
|
||||||
|
2. fetch only selected skill documents for context
|
||||||
|
3. keep slash commands for deterministic fallback flows
|
||||||
|
|
||||||
|
When resource attachment is unavailable in the active session, use ResourcesAsTools first, then thin catalog discovery tools as parity fallback:
|
||||||
|
|
||||||
|
1. `list_resources`
|
||||||
|
2. `read_resource`
|
||||||
|
3. `search_patterns`
|
||||||
|
4. `get_pattern_by_id`
|
||||||
|
5. `get_skill_document_by_id`
|
||||||
|
|
||||||
|
Canonical naming policy:
|
||||||
|
|
||||||
|
1. Prefer the five canonical tool names above in prompts and instructions.
|
||||||
|
2. For compatibility with clients that emit `catalog_*` naming, the server also exposes:
|
||||||
|
- `catalog_search_patterns`
|
||||||
|
- `catalog_get_pattern_by_id`
|
||||||
|
- `catalog_get_skill_document_by_id`
|
||||||
|
3. Canonical and compatibility alias tools return equivalent payloads for the same input.
|
||||||
|
|
||||||
|
The first two are generated from the canonical resource surface and should be preferred in tool-only clients.
|
||||||
|
|
||||||
|
These should stay read-only, minimal, and schema-aligned with catalog resources.
|
||||||
|
|
||||||
|
For very large tool catalogs, server operators can optionally enable tool search mode (`regex` or `bm25`) while keeping `list_resources` and `read_resource` pinned as always-visible fallback tools.
|
||||||
|
|
||||||
|
## What To Type In Copilot Chat
|
||||||
|
|
||||||
|
Use prompts that tell Copilot which MCP feature path to take.
|
||||||
|
|
||||||
|
### If `MCP Resources...` is available
|
||||||
|
|
||||||
|
Use the resource attachment UI first, then ask Copilot to work from the attached material.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```text
|
||||||
|
I attached the catalog resources and the FastAPI async SQLAlchemy modernization skill document. Use that context to propose a migration plan for this repo.
|
||||||
|
```
|
||||||
|
|
||||||
|
If you want to keep the attachment sequence explicit, use:
|
||||||
|
|
||||||
|
```text
|
||||||
|
I attached personal-mcp catalog resources first. Use them to identify the best matching skill, then work only from the selected skill document.
|
||||||
|
```
|
||||||
|
|
||||||
|
### If only tools are available
|
||||||
|
|
||||||
|
Ask Copilot to explicitly use resource-backed tools first.
|
||||||
|
|
||||||
|
Example resource-backed prompt:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Use personal-mcp tool fallback by first calling list_resources, then read_resource for resource://catalog/skills_index and the selected resource://skills/<skill-id>/document URI. Use only that loaded skill context in your answer.
|
||||||
|
```
|
||||||
|
|
||||||
|
If needed, use the thin catalog tools.
|
||||||
|
|
||||||
|
Example discovery prompt:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Use the personal-mcp catalog tools to search for the most relevant skill for FastAPI async SQLAlchemy modernization. Then load the selected skill document and use it as context for your answer.
|
||||||
|
```
|
||||||
|
|
||||||
|
Example direct-load prompt:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Call get_skill_document_by_id for async-fastapi-sqlmodel and use that document as the main context for this task.
|
||||||
|
```
|
||||||
|
|
||||||
|
Example bounded-selection prompt:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Search personal-mcp skills for NiceGUI UI customization, select at most 2 strong matches, load the best skill document, and answer using only that material plus the workspace code.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Repo Instructions Example
|
||||||
|
|
||||||
|
Repo instructions are the best place to teach Copilot when MCP content is relevant and which path to prefer.
|
||||||
|
|
||||||
|
If you add a repo-level `copilot-instructions.md`, keep the rule simple: prefer catalog-first discovery, keep loaded skill context small, and fall back to tools when resource attachment is unavailable.
|
||||||
|
|
||||||
|
Instructions can strongly steer behavior, but they do not guarantee that VS Code will auto-attach MCP resources for a request. For reliable resource use, either attach resources explicitly or prompt Copilot to use the fallback tools.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```md
|
||||||
|
# MCP Usage
|
||||||
|
|
||||||
|
When a task may benefit from personal-mcp skills, use this sequence:
|
||||||
|
|
||||||
|
1. Start with personal-mcp catalog discovery when the task appears to match documented implementation patterns.
|
||||||
|
2. Prefer MCP resources when the chat surface exposes resource attachment.
|
||||||
|
3. If MCP resource attachment is unavailable, use `list_resources`/`read_resource` first, then thin catalog tools if needed.
|
||||||
|
4. Load only the most relevant skill document or at most 2 skill documents.
|
||||||
|
5. Treat skill documents as guidance, then reconcile them with the actual repository code before making changes.
|
||||||
|
|
||||||
|
Preferred discovery order:
|
||||||
|
|
||||||
|
1. `resource://catalog/skills_index`
|
||||||
|
2. `resource://catalog/skills/{skill_id}`
|
||||||
|
3. `resource://skills/<skill-id>/document`
|
||||||
|
4. `resource://skills/<skill-id>/references/<ref-id>` when needed
|
||||||
|
|
||||||
|
Tool fallback order:
|
||||||
|
|
||||||
|
1. `list_resources`
|
||||||
|
2. `read_resource`
|
||||||
|
3. `search_patterns`
|
||||||
|
4. `get_pattern_by_id`
|
||||||
|
5. `get_skill_document_by_id`
|
||||||
|
|
||||||
|
If confidence is low after catalog discovery, ask one clarifying question before loading more skill documents.
|
||||||
|
```
|
||||||
|
|
||||||
|
That instruction style does two useful things:
|
||||||
|
|
||||||
|
1. it tells Copilot to prefer the MCP server when relevant without forcing it on every prompt
|
||||||
|
2. it keeps context size bounded so skill loading does not become noisy or expensive
|
||||||
|
|
||||||
|
If you want stronger behavior, add one more line that names the MCP server directly:
|
||||||
|
|
||||||
|
```md
|
||||||
|
Use the `personal-mcp` server for skill discovery whenever the task involves documented implementation patterns available from the catalog.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Known Gotcha
|
||||||
|
|
||||||
|
A successful `resources/list` response from the server does not guarantee the resource picker appears in every Copilot session type. UI availability is session-capability-dependent.
|
||||||
|
|
||||||
|
## Further Reading
|
||||||
|
|
||||||
|
### VS Code docs
|
||||||
|
|
||||||
|
1. [Add and manage MCP servers](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
||||||
|
2. [MCP configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration)
|
||||||
|
3. [Manage context for AI](https://code.visualstudio.com/docs/chat/copilot-chat-context)
|
||||||
|
4. [AI features cheat sheet](https://code.visualstudio.com/docs/agents/reference/ai-features-cheat-sheet)
|
||||||
|
|
||||||
|
### Project docs
|
||||||
|
|
||||||
|
1. [Resource-First Pattern Module Architecture](./architecture.md)
|
||||||
|
2. [Static Docs Hosting Pattern](./mcp_layout.md)
|
||||||
|
3. [Skill Usage Mechanics](./usage.md)
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/rocket
|
||||||
|
---
|
||||||
|
|
||||||
|
# Personal MCP
|
||||||
|
|
||||||
|
This project is a document library of software patterns, best practices, and structured references to external documentation. The same markdown files are published through two equivalent surfaces, so human-readable docs and MCP resources stay aligned.
|
||||||
|
|
||||||
|
## MCP Server
|
||||||
|
|
||||||
|
An [MCP server](https://modelcontextprotocol.io/docs/getting-started/intro) at `/mcp` provides context for AI systems. The markdown files are exposed as [resources](https://modelcontextprotocol.io/docs/learn/server-concepts#resources) and are structured to be easily consumed by [MCP clients](https://modelcontextprotocol.io/docs/learn/client-concepts), such as VS Code.
|
||||||
|
|
||||||
|
## Docs
|
||||||
|
|
||||||
|
A website at `/docs` for humans to read and review.
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
Install dependencies first:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv sync
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the app locally with the static docs rebuilt first, using [Uvicorn factory mode](https://www.uvicorn.org/settings/#application):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run zensical build && uv run uvicorn personal_mcp.main:create_app --factory --host 127.0.0.1 --port 8765
|
||||||
|
```
|
||||||
|
|
||||||
|
Build and run the Docker image with the same exposed port:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t personal-mcp . && docker run --rm -p 8765:8765 personal-mcp
|
||||||
|
```
|
||||||
|
|
||||||
|
When the server is running, the health check is available at `/healthz` and the generated docs are available at `/docs/`.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- [Resource-First Pattern Module Architecture](./architecture.md)
|
||||||
|
- [Contracts](./contracts/index.md)
|
||||||
|
- [Content Contract](./contracts/index.md#content-contract)
|
||||||
|
- [Frontmatter Contract](./contracts/frontmatter.md)
|
||||||
|
- [URI Contract](./contracts/uris.md)
|
||||||
|
- [Static Docs Hosting Pattern](./mcp_layout.md)
|
||||||
|
- [Skill Usage Mechanics](./usage.md)
|
||||||
|
- [Copilot MCP Mechanics](./copilot.md)
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/server
|
||||||
|
---
|
||||||
|
|
||||||
|
# Static Docs Hosting Pattern
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This document describes the completed layout and runtime pattern used to host a pre-built static documentation site from the same FastAPI app process that runs the FastMCP server.
|
||||||
|
|
||||||
|
This design intentionally avoids runtime docs rendering and avoids a separate docs hosting service.
|
||||||
|
|
||||||
|
It also treats Markdown as the single source of truth for both MCP resources and published docs.
|
||||||
|
|
||||||
|
## Completed-State Layout
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
---
|
||||||
|
config:
|
||||||
|
treeView:
|
||||||
|
rowIndent: 40
|
||||||
|
lineThickness: 2
|
||||||
|
themeVariables:
|
||||||
|
treeView:
|
||||||
|
labelColor: '#FFFFFF'
|
||||||
|
lineColor: '#FFFFFF'
|
||||||
|
---
|
||||||
|
treeView-beta
|
||||||
|
"project-root"
|
||||||
|
"pyproject.toml"
|
||||||
|
"uv.lock"
|
||||||
|
"zensical.toml"
|
||||||
|
"docs"
|
||||||
|
"index.md"
|
||||||
|
"<project-docs>.md"
|
||||||
|
"contracts"
|
||||||
|
"index.md"
|
||||||
|
"<contract-pages>.md"
|
||||||
|
"mcp_layout.md"
|
||||||
|
"prompts"
|
||||||
|
"<prompt-id>"
|
||||||
|
"PROMPT.md"
|
||||||
|
"references"
|
||||||
|
"skills"
|
||||||
|
"<skill-id>"
|
||||||
|
"SKILL.md"
|
||||||
|
"references"
|
||||||
|
"<reference>.md"
|
||||||
|
"site"
|
||||||
|
"static build output"
|
||||||
|
"src"
|
||||||
|
"personal_mcp"
|
||||||
|
"__init__.py"
|
||||||
|
"main.py"
|
||||||
|
"mcp.py"
|
||||||
|
"catalog"
|
||||||
|
"<catalog-modules>.py"
|
||||||
|
"registry"
|
||||||
|
"<registry-modules>.py"
|
||||||
|
"web"
|
||||||
|
"<web-modules>.py"
|
||||||
|
"skills"
|
||||||
|
"<skills-modules>.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
1. docs contains both project-authored pages and the canonical skill Markdown tree.
|
||||||
|
2. site contains static build output only.
|
||||||
|
3. docs/skills contains canonical skill Markdown and reference Markdown.
|
||||||
|
4. docs/prompts contains canonical prompt Markdown used for prompt catalog and document surfaces.
|
||||||
|
5. MCP resources and docs site read from the same Markdown sources.
|
||||||
|
|
||||||
|
## Runtime Composition
|
||||||
|
|
||||||
|
The runtime process serves two surfaces:
|
||||||
|
|
||||||
|
1. MCP protocol surface from FastMCP
|
||||||
|
2. Static docs surface from FastAPI static mount
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[Docs Registry Loader] --> B[Validated In-Memory Registry]
|
||||||
|
B --> C[FastMCP Resource Registration]
|
||||||
|
C --> D[MCP Transport]
|
||||||
|
C --> E[FastAPI Application]
|
||||||
|
E --> F[Static Mount /docs]
|
||||||
|
F --> G[Zensical site output directory]
|
||||||
|
```
|
||||||
|
|
||||||
|
Runtime guarantees:
|
||||||
|
|
||||||
|
1. Docs registry load and validation happen before resource exposure.
|
||||||
|
2. Duplicate resource and template registration fails startup (`on_duplicate="error"`).
|
||||||
|
3. Resource registration is metadata-driven from SKILL frontmatter and reference manifests.
|
||||||
|
4. Legacy per-skill Python servers and `metadata.yaml` sidecars are not part of the runtime.
|
||||||
|
|
||||||
|
## Build and Publish Flow
|
||||||
|
|
||||||
|
The docs flow is pre-build only.
|
||||||
|
|
||||||
|
1. Read authored docs pages and skill markdown sources.
|
||||||
|
2. Build static site with Zensical into site.
|
||||||
|
3. Start app and serve site directory as static files.
|
||||||
|
|
||||||
|
No runtime markdown conversion is required.
|
||||||
|
|
||||||
|
## Content Merge Pattern
|
||||||
|
|
||||||
|
The published docs site always contains both:
|
||||||
|
|
||||||
|
1. Project-authored docs pages
|
||||||
|
2. Skill Markdown content from docs/skills/*/SKILL.md and references
|
||||||
|
|
||||||
|
This ensures the public docs reflect architectural guidance and the exact Markdown served by MCP.
|
||||||
|
|
||||||
|
## Markdown-to-Resource Mapping
|
||||||
|
|
||||||
|
MCP resources map directly to canonical Markdown documents.
|
||||||
|
|
||||||
|
Example mapping model:
|
||||||
|
|
||||||
|
1. docs/skills/<skill-id>/SKILL.md -> resource://skills/<skill_id>/document
|
||||||
|
2. docs/skills/<skill-id>/references/<file>.md -> resource://skills/<skill_id>/references/<ref_id> (via frontmatter references manifest)
|
||||||
|
3. docs/<path>.md -> resource://docs/{path*}
|
||||||
|
|
||||||
|
Catalog discovery resources are:
|
||||||
|
|
||||||
|
1. resource://catalog/skills_index
|
||||||
|
2. resource://catalog/skills_index{?q,tag,capability,cursor,limit}
|
||||||
|
3. resource://catalog/skills/{skill_id}
|
||||||
|
4. resource://catalog/prompts_index
|
||||||
|
5. resource://catalog/prompts_index{?q,tag,cursor,limit}
|
||||||
|
6. resource://catalog/prompts/{prompt_id}
|
||||||
|
|
||||||
|
Registry-backed registration details:
|
||||||
|
|
||||||
|
1. `resource://skills/{skill_id}/document` resolves to each skill's SKILL.md.
|
||||||
|
2. `resource://skills/{skill_id}/references/{ref_id}` resolves through frontmatter reference manifests.
|
||||||
|
3. `resource://docs/{path*}` resolves normalized markdown paths under `docs/`.
|
||||||
|
4. Resource metadata includes explicit mime type and read-only/idempotent annotations.
|
||||||
|
|
||||||
|
When clients cannot attach MCP resources directly, thin catalog tools may retrieve the same underlying skill documents indirectly. This does not create a second content source.
|
||||||
|
|
||||||
|
## URI Compatibility Policy
|
||||||
|
|
||||||
|
1. Canonical URIs are the only supported URIs in this runtime.
|
||||||
|
2. No backward-compatibility aliases or dual registration paths are maintained.
|
||||||
|
3. Contract changes should update clients to canonical URIs directly.
|
||||||
|
|
||||||
|
## Why This Pattern
|
||||||
|
|
||||||
|
### Operational Simplicity
|
||||||
|
|
||||||
|
One application process serves both protocol and static docs surfaces.
|
||||||
|
|
||||||
|
### Deterministic Docs
|
||||||
|
|
||||||
|
Published docs are immutable static assets for a given build.
|
||||||
|
|
||||||
|
### Documentation Fidelity
|
||||||
|
|
||||||
|
The docs site and MCP resources resolve from the same Markdown sources.
|
||||||
|
|
||||||
|
### Maintainer Experience
|
||||||
|
|
||||||
|
Authors continue to work in markdown while resource contracts remain machine-consumable.
|
||||||
|
|
||||||
|
## FastAPI Static Mount Expectations
|
||||||
|
|
||||||
|
The FastAPI app is expected to:
|
||||||
|
|
||||||
|
1. Mount static directory containing Zensical output.
|
||||||
|
2. Serve index and asset files from that directory.
|
||||||
|
3. Keep docs route stable across releases.
|
||||||
|
|
||||||
|
Recommended route conventions:
|
||||||
|
|
||||||
|
1. /docs for static site root
|
||||||
|
2. /docs/* for static assets and page routes
|
||||||
|
|
||||||
|
## Update Lifecycle
|
||||||
|
|
||||||
|
For each documentation update:
|
||||||
|
|
||||||
|
1. Edit authored docs and skill markdown content.
|
||||||
|
2. Rebuild static site.
|
||||||
|
3. Restart runtime if needed.
|
||||||
|
|
||||||
|
This keeps docs publication explicit and predictable.
|
||||||
|
|
||||||
|
## Example Source Material
|
||||||
|
|
||||||
|
Existing reference docs remain valid content inputs in this pattern:
|
||||||
|
|
||||||
|
1. docs/skills/pytesting/references/pytest-docs.md
|
||||||
|
2. docs/skills/python-logging/references/python-logging-docs.md
|
||||||
|
3. docs/skills/python-logging/references/json-file-logging.md
|
||||||
|
4. docs/skills/fastapi-uv-docker/references/fastapi-best-practices.md
|
||||||
|
|
||||||
|
These are source documents, not deployment artifacts.
|
||||||
+28
-18
@@ -1,21 +1,33 @@
|
|||||||
---
|
---
|
||||||
icon: lucide/messages-square
|
name: authoring
|
||||||
prompt:
|
|
||||||
version: "1.0.0"
|
|
||||||
description: Provide a practical checklist and baseline template for authoring docs-first MCP modules and repository-specific Copilot instruction shims.
|
description: Provide a practical checklist and baseline template for authoring docs-first MCP modules and repository-specific Copilot instruction shims.
|
||||||
tags: [authoring, mcp, fastmcp, copilot, prompts, scaffolding]
|
x-personal-mcp:
|
||||||
|
id: authoring
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- authoring
|
||||||
|
- mcp
|
||||||
|
- fastmcp
|
||||||
|
- copilot
|
||||||
|
- prompts
|
||||||
|
- scaffolding
|
||||||
|
capabilities:
|
||||||
|
- resource://prompts/authoring/document
|
||||||
arguments:
|
arguments:
|
||||||
artifact_type:
|
artifact_type:
|
||||||
description: Artifact type to create.
|
title: Artifact type
|
||||||
|
description: "Enum (case-sensitive): skill | prompt | shim."
|
||||||
required: true
|
required: true
|
||||||
choices: [skill, prompt, shim]
|
|
||||||
artifact_id:
|
artifact_id:
|
||||||
|
title: Artifact id
|
||||||
description: Lowercase kebab-case id for the module or shim.
|
description: Lowercase kebab-case id for the module or shim.
|
||||||
required: true
|
required: true
|
||||||
goal:
|
goal:
|
||||||
description: One-sentence capability statement.
|
title: Goal
|
||||||
|
description: One-sentence capability statement describing what to create and when to use it.
|
||||||
required: true
|
required: true
|
||||||
scope_glob:
|
scope_glob:
|
||||||
|
title: Scope glob
|
||||||
description: Optional applyTo glob for shim outputs.
|
description: Optional applyTo glob for shim outputs.
|
||||||
required: false
|
required: false
|
||||||
---
|
---
|
||||||
@@ -24,13 +36,6 @@ prompt:
|
|||||||
|
|
||||||
Use this prompt to author or update docs-first MCP modules in this repository, including repository-specific Copilot thin shims.
|
Use this prompt to author or update docs-first MCP modules in this repository, including repository-specific Copilot thin shims.
|
||||||
|
|
||||||
## Supplied Inputs
|
|
||||||
|
|
||||||
- `artifact_type`: {{artifact_type}}
|
|
||||||
- `artifact_id`: {{artifact_id}}
|
|
||||||
- `goal`: {{goal}}
|
|
||||||
- `scope_glob`: {{scope_glob}}
|
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
1. artifact_type: one of skill, prompt, shim
|
1. artifact_type: one of skill, prompt, shim
|
||||||
@@ -46,7 +51,7 @@ Load only what matches the requested artifact:
|
|||||||
2. Prompt metadata and structure: [Prompt Contract](../../contracts/prompt.md)
|
2. Prompt metadata and structure: [Prompt Contract](../../contracts/prompt.md)
|
||||||
3. Skill metadata and structure (only for skill outputs): [Skill Contract](../../contracts/skill_contract.md)
|
3. Skill metadata and structure (only for skill outputs): [Skill Contract](../../contracts/skill_contract.md)
|
||||||
4. Thin shim mechanics and path binding: [Skill Usage Mechanics](../../usage.md)
|
4. Thin shim mechanics and path binding: [Skill Usage Mechanics](../../usage.md)
|
||||||
5. Copilot resource attachment behavior: [Copilot MCP Mechanics](../../copilot.md)
|
5. Copilot resource attachment and fallback behavior: [Copilot MCP Mechanics](../../copilot.md)
|
||||||
|
|
||||||
## Workflow
|
## Workflow
|
||||||
|
|
||||||
@@ -64,9 +69,14 @@ Load only what matches the requested artifact:
|
|||||||
7. Produce only the requested artifact type.
|
7. Produce only the requested artifact type.
|
||||||
8. Keep guidance deterministic and minimal, with explicit references to source docs.
|
8. Keep guidance deterministic and minimal, with explicit references to source docs.
|
||||||
9. If artifact_type is shim:
|
9. If artifact_type is shim:
|
||||||
- bind one applyTo scope to one `skill://<name>/SKILL.md` resource URI
|
- bind one applyTo scope to one primary skill resource URI
|
||||||
- use MCP resource attachment
|
- prefer MCP resource attachment first
|
||||||
- inspect the selected skill's `_manifest` only when supporting material is needed
|
- if resource attachment is unavailable, use fallback tool order:
|
||||||
|
1. list_resources
|
||||||
|
2. read_resource
|
||||||
|
3. search_patterns
|
||||||
|
4. get_pattern_by_id
|
||||||
|
5. get_skill_document_by_id
|
||||||
10. Return created or updated file paths and any validation commands that should be run.
|
10. Return created or updated file paths and any validation commands that should be run.
|
||||||
|
|
||||||
## Output Contract
|
## Output Contract
|
||||||
+20
-15
@@ -1,21 +1,33 @@
|
|||||||
---
|
---
|
||||||
icon: lucide/messages-square
|
name: greenfield-architecture
|
||||||
prompt:
|
|
||||||
version: "1.0.0"
|
|
||||||
description: Research established patterns and design a high-level architecture for a new app or library with explicit tradeoffs and test strategy.
|
description: Research established patterns and design a high-level architecture for a new app or library with explicit tradeoffs and test strategy.
|
||||||
tags: [architecture, planning, greenfield, design, testing, prompts]
|
x-personal-mcp:
|
||||||
|
id: greenfield-architecture
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- planning
|
||||||
|
- greenfield
|
||||||
|
- design
|
||||||
|
- testing
|
||||||
|
- prompts
|
||||||
|
capabilities:
|
||||||
|
- resource://prompts/greenfield-architecture/document
|
||||||
arguments:
|
arguments:
|
||||||
scope_type:
|
scope_type:
|
||||||
description: Scope type to design.
|
title: Scope type
|
||||||
|
description: "Scope type: app or library."
|
||||||
required: true
|
required: true
|
||||||
choices: [app, library]
|
|
||||||
intent_document:
|
intent_document:
|
||||||
description: Optional full document describing goals and context.
|
title: Intent document
|
||||||
|
description: Optional full document describing goals, context, and desired outcomes.
|
||||||
required: false
|
required: false
|
||||||
problem_domain:
|
problem_domain:
|
||||||
description: Problem domain and business goal.
|
title: Problem domain
|
||||||
|
description: Domain and business goal for the new app or library when no full intent document is provided.
|
||||||
required: false
|
required: false
|
||||||
constraints:
|
constraints:
|
||||||
|
title: Constraints
|
||||||
description: Runtime, deployment, and non-functional constraints.
|
description: Runtime, deployment, and non-functional constraints.
|
||||||
required: false
|
required: false
|
||||||
---
|
---
|
||||||
@@ -24,13 +36,6 @@ prompt:
|
|||||||
|
|
||||||
Use this prompt to design a new software app or library architecture in generic terms.
|
Use this prompt to design a new software app or library architecture in generic terms.
|
||||||
|
|
||||||
## Supplied Inputs
|
|
||||||
|
|
||||||
- `scope_type`: {{scope_type}}
|
|
||||||
- `intent_document`: {{intent_document}}
|
|
||||||
- `problem_domain`: {{problem_domain}}
|
|
||||||
- `constraints`: {{constraints}}
|
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
1. intent_document: optional full document that explains goals, context, constraints, and desired outcomes
|
1. intent_document: optional full document that explains goals, context, constraints, and desired outcomes
|
||||||
+37
-27
@@ -1,21 +1,29 @@
|
|||||||
---
|
---
|
||||||
icon: lucide/messages-square
|
name: mcp-consumer-repo-shim
|
||||||
prompt:
|
description: Create one repository-specific thin shim instruction file that binds a file scope to a user-selected Personal MCP skill resource and enforces resource-first Copilot retrieval behavior.
|
||||||
version: "1.0.0"
|
x-personal-mcp:
|
||||||
description: Create one repository-specific thin shim instruction file that binds a file scope to a user-selected Personal MCP skill resource.
|
id: mcp-consumer-repo-shim
|
||||||
tags: [copilot, mcp, instructions, shims, prompts]
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- copilot
|
||||||
|
- mcp
|
||||||
|
- instructions
|
||||||
|
- shims
|
||||||
|
- prompts
|
||||||
|
capabilities:
|
||||||
|
- resource://prompts/mcp-consumer-repo-shim/document
|
||||||
arguments:
|
arguments:
|
||||||
apply_to_glob:
|
apply_to_glob:
|
||||||
description: File glob scope for the shim applyTo field.
|
description: File glob scope for the shim applyTo field, such as tests/** or **/*.md.
|
||||||
required: true
|
required: true
|
||||||
primary_skill_resource:
|
primary_skill_resource:
|
||||||
description: Primary native skill:// resource URI.
|
description: Primary skill resource URI, usually resource://skills/<skill-id>/document.
|
||||||
required: true
|
required: true
|
||||||
shim_title:
|
shim_title:
|
||||||
description: Optional human-readable instruction shim name.
|
description: Human-readable name for the instruction shim frontmatter.
|
||||||
required: false
|
required: false
|
||||||
companion_docs_page:
|
companion_docs_page:
|
||||||
description: Optional relative companion documentation link.
|
description: Optional relative docs link for human-facing companion guidance.
|
||||||
required: false
|
required: false
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -23,13 +31,6 @@ prompt:
|
|||||||
|
|
||||||
Use this prompt to generate exactly one repository-scoped Copilot instruction shim for an MCP consumer repository.
|
Use this prompt to generate exactly one repository-scoped Copilot instruction shim for an MCP consumer repository.
|
||||||
|
|
||||||
## Supplied Inputs
|
|
||||||
|
|
||||||
- `apply_to_glob`: {{apply_to_glob}}
|
|
||||||
- `primary_skill_resource`: {{primary_skill_resource}}
|
|
||||||
- `shim_title`: {{shim_title}}
|
|
||||||
- `companion_docs_page`: {{companion_docs_page}}
|
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
- Required:
|
- Required:
|
||||||
@@ -44,26 +45,30 @@ Use this prompt to generate exactly one repository-scoped Copilot instruction sh
|
|||||||
Load only sections relevant to the requested shim:
|
Load only sections relevant to the requested shim:
|
||||||
|
|
||||||
1. Thin shim pattern and scope guidance: [Skill Usage Mechanics](../../usage.md)
|
1. Thin shim pattern and scope guidance: [Skill Usage Mechanics](../../usage.md)
|
||||||
2. VS Code Copilot MCP resource behavior: [Copilot MCP Mechanics](../../copilot.md)
|
2. VS Code Copilot MCP behavior and fallback mechanics: [Copilot MCP Mechanics](../../copilot.md)
|
||||||
3. Authoring workflow and validation checklist: [Authoring Guide](../../authoring.md)
|
3. Authoring workflow and validation checklist: [Authoring Guide](../../authoring.md)
|
||||||
4. Instruction metadata expectations and examples: [Copilot customization skill](../../skills/copilot-customization/SKILL.md)
|
4. Instruction metadata expectations and examples: [Copilot customization skill](../../skills/copilot-customization/SKILL.md)
|
||||||
|
|
||||||
## Workflow
|
## Workflow
|
||||||
|
|
||||||
1. Validate that apply_to_glob and primary_skill_resource are present.
|
1. Validate that apply_to_glob and primary_skill_resource are present.
|
||||||
2. Validate that primary_skill_resource uses the `skill://<skill-name>/SKILL.md` form.
|
2. If either value is missing or ambiguous, ask exactly one clarifying question before generating output.
|
||||||
3. If either value is missing or ambiguous, ask exactly one clarifying question before generating output.
|
3. Generate one .instructions.md file content block only.
|
||||||
4. Generate one .instructions.md file content block only.
|
4. Keep the shim concise and deterministic:
|
||||||
5. Keep the shim concise and deterministic:
|
|
||||||
- include YAML frontmatter with name, description, and applyTo
|
- include YAML frontmatter with name, description, and applyTo
|
||||||
- include a primary rule that uses the selected primary_skill_resource first
|
- include a primary rule that uses the selected primary_skill_resource first
|
||||||
- include a bounded execution pattern (load primary doc, apply only relevant sections, keep edits minimal)
|
- include a bounded execution pattern (load primary doc, apply only relevant sections, keep edits minimal)
|
||||||
6. Include VS Code/Copilot integration mechanics in the shim body:
|
5. Include VS Code/Copilot integration mechanics in the shim body:
|
||||||
- use MCP resource attachment
|
- prefer MCP resource attachment when available
|
||||||
- inspect `_manifest` only when the task needs supporting material
|
- if attachment is unavailable, use tool fallback order:
|
||||||
|
1. list_resources
|
||||||
|
2. read_resource
|
||||||
|
3. search_patterns
|
||||||
|
4. get_pattern_by_id
|
||||||
|
5. get_skill_document_by_id
|
||||||
- ask one clarifying question when confidence is low
|
- ask one clarifying question when confidence is low
|
||||||
7. If companion_docs_page is provided, include it as a companion docs link line.
|
6. If companion_docs_page is provided, include it as a companion docs link line.
|
||||||
8. Do not generate additional files, code changes, or batch shim packs.
|
7. Do not generate additional files, code changes, or batch shim packs.
|
||||||
|
|
||||||
## Output Format
|
## Output Format
|
||||||
|
|
||||||
@@ -93,7 +98,12 @@ Execution pattern:
|
|||||||
2. Apply only sections relevant to the file being edited.
|
2. Apply only sections relevant to the file being edited.
|
||||||
3. Keep edits minimal and aligned with repository conventions.
|
3. Keep edits minimal and aligned with repository conventions.
|
||||||
4. Prefer MCP resource attachment when available in the current chat surface.
|
4. Prefer MCP resource attachment when available in the current chat surface.
|
||||||
5. Read the selected skill's `_manifest` only when supporting material is needed.
|
5. If MCP resource attachment is unavailable, use tool fallback in this order:
|
||||||
|
1. list_resources
|
||||||
|
2. read_resource
|
||||||
|
3. search_patterns
|
||||||
|
4. get_pattern_by_id
|
||||||
|
5. get_skill_document_by_id
|
||||||
6. If confidence is low, ask one clarifying question before editing.
|
6. If confidence is low, ask one clarifying question before editing.
|
||||||
|
|
||||||
Companion docs page: <optional-relative-doc-link>
|
Companion docs page: <optional-relative-doc-link>
|
||||||
+14
-15
@@ -1,9 +1,16 @@
|
|||||||
---
|
---
|
||||||
icon: lucide/messages-square
|
name: pytest-fill-scaffold
|
||||||
prompt:
|
description: Fill scaffolded pytest test methods with assertions, fixtures, and minimal test data while preserving concise test names and one-line intent docstrings.
|
||||||
version: "1.0.0"
|
x-personal-mcp:
|
||||||
description: Fill scaffolded pytest methods with assertions, fixtures, and minimal test data while preserving reviewed structure.
|
id: pytest-fill-scaffold
|
||||||
tags: [pytest, testing, scaffolding, prompts]
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- pytest
|
||||||
|
- testing
|
||||||
|
- scaffolding
|
||||||
|
- prompts
|
||||||
|
capabilities:
|
||||||
|
- resource://prompts/pytest-fill-scaffold/document
|
||||||
arguments:
|
arguments:
|
||||||
target_files:
|
target_files:
|
||||||
description: Target test file paths under tests/.
|
description: Target test file paths under tests/.
|
||||||
@@ -11,12 +18,11 @@ prompt:
|
|||||||
stack:
|
stack:
|
||||||
description: Runtime stack type for fixture and marker choices.
|
description: Runtime stack type for fixture and marker choices.
|
||||||
required: true
|
required: true
|
||||||
choices: [pure-python, fastapi, sqlalchemy-sync, sqlalchemy-async, mixed]
|
|
||||||
strategy:
|
strategy:
|
||||||
description: Optional minimal or comprehensive implementation preference.
|
description: Balance between minimal and comprehensive implementation.
|
||||||
required: false
|
required: false
|
||||||
marker_lane:
|
marker_lane:
|
||||||
description: Optional pytest marker lane.
|
description: Preferred marker lane when applicable.
|
||||||
required: false
|
required: false
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -24,13 +30,6 @@ prompt:
|
|||||||
|
|
||||||
Use this prompt after test scaffolding exists and method names/docstrings are already in place.
|
Use this prompt after test scaffolding exists and method names/docstrings are already in place.
|
||||||
|
|
||||||
## Supplied Inputs
|
|
||||||
|
|
||||||
- `target_files`: {{target_files}}
|
|
||||||
- `stack`: {{stack}}
|
|
||||||
- `strategy`: {{strategy}}
|
|
||||||
- `marker_lane`: {{marker_lane}}
|
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
- Target test file(s) under tests/.
|
- Target test file(s) under tests/.
|
||||||
+16
-17
@@ -1,22 +1,28 @@
|
|||||||
---
|
---
|
||||||
icon: lucide/messages-square
|
name: pytest-scaffold
|
||||||
prompt:
|
description: Plan and optionally scaffold pytest file and class structure for selected Python modules while preserving concise behavior-focused test names and one-line intent docstrings.
|
||||||
version: "1.0.0"
|
x-personal-mcp:
|
||||||
description: Plan and optionally scaffold pytest file and class structure for selected Python modules.
|
id: pytest-scaffold
|
||||||
tags: [pytest, testing, scaffolding, prompts]
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- pytest
|
||||||
|
- testing
|
||||||
|
- scaffolding
|
||||||
|
- prompts
|
||||||
|
capabilities:
|
||||||
|
- resource://prompts/pytest-scaffold/document
|
||||||
arguments:
|
arguments:
|
||||||
target_modules:
|
target_modules:
|
||||||
description: Target module paths under src/.
|
description: Target module path(s) under src/.
|
||||||
required: true
|
required: true
|
||||||
mode:
|
mode:
|
||||||
description: Whether to plan only or create scaffold files.
|
description: Execution mode, either plan-only or scaffold.
|
||||||
required: true
|
required: true
|
||||||
choices: [plan-only, scaffold]
|
|
||||||
path_strategy:
|
path_strategy:
|
||||||
description: Optional src-to-tests path mapping preference.
|
description: Optional mapping preference for src to tests paths.
|
||||||
required: false
|
required: false
|
||||||
naming_style:
|
naming_style:
|
||||||
description: Optional concise test naming preference.
|
description: Optional preference for concise method naming style.
|
||||||
required: false
|
required: false
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -24,13 +30,6 @@ prompt:
|
|||||||
|
|
||||||
Use this prompt to consistently plan and scaffold pytest test modules for selected Python source modules.
|
Use this prompt to consistently plan and scaffold pytest test modules for selected Python source modules.
|
||||||
|
|
||||||
## Supplied Inputs
|
|
||||||
|
|
||||||
- `target_modules`: {{target_modules}}
|
|
||||||
- `mode`: {{mode}}
|
|
||||||
- `path_strategy`: {{path_strategy}}
|
|
||||||
- `naming_style`: {{naming_style}}
|
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
- Required:
|
- Required:
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
---
|
||||||
|
icon: lucide/shield-check
|
||||||
|
---
|
||||||
|
|
||||||
|
# Securing Remote Access
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
This project exposes two related surfaces from the same runtime:
|
||||||
|
|
||||||
|
1. a static documentation site under `/docs`
|
||||||
|
2. a Streamable HTTP MCP endpoint under `/mcp`
|
||||||
|
|
||||||
|
The same Markdown content backs both surfaces. For the current project shape, the MCP server is resource-first and primarily exposes public skill and documentation text. It is not intended to expose secrets, private data, shell access, filesystem access, or tools with side effects.
|
||||||
|
|
||||||
|
The expected deployment path is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Public internet
|
||||||
|
-> Cloudflare Tunnel
|
||||||
|
-> Caddy
|
||||||
|
-> personal-mcp container
|
||||||
|
```
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
For the current use case, heavy application-level authentication is not required.
|
||||||
|
|
||||||
|
The recommended posture is:
|
||||||
|
|
||||||
|
1. Keep the service behind Cloudflare Tunnel and Caddy.
|
||||||
|
2. Do not expose the container port directly to the public internet.
|
||||||
|
3. Treat everything exposed through MCP as publishable public documentation.
|
||||||
|
4. Add stronger authentication only if the MCP surface later includes sensitive content or tools with meaningful side effects.
|
||||||
|
|
||||||
|
This keeps the deployment simple while preserving a clear upgrade path.
|
||||||
|
|
||||||
|
## Tradeoffs
|
||||||
|
|
||||||
|
### Leaving `/mcp` Public
|
||||||
|
|
||||||
|
This is acceptable if `/mcp` exposes only the same public Markdown already available through `/docs`.
|
||||||
|
|
||||||
|
Benefits:
|
||||||
|
|
||||||
|
1. lowest operational friction
|
||||||
|
2. fewer compatibility issues with MCP clients
|
||||||
|
3. no need to implement OAuth, mTLS, JWT validation, or custom auth middleware
|
||||||
|
4. consistent with the project assumption that documentation content is public
|
||||||
|
|
||||||
|
Risks:
|
||||||
|
|
||||||
|
1. random scraping, probing, or fuzzing of a machine endpoint
|
||||||
|
2. possible bandwidth or CPU nuisance traffic
|
||||||
|
3. accidental future exposure if new tools or private resources are added
|
||||||
|
4. less control over who can use the MCP endpoint
|
||||||
|
|
||||||
|
### Protecting `/mcp` With Cloudflare Access
|
||||||
|
|
||||||
|
Cloudflare Access can add a lightweight gate using GitHub, Google, one-time PIN, or service tokens.
|
||||||
|
|
||||||
|
Benefits:
|
||||||
|
|
||||||
|
1. reduces random internet traffic
|
||||||
|
2. requires little app code
|
||||||
|
3. works well for a small trusted team
|
||||||
|
4. provides logs and centralized access control
|
||||||
|
|
||||||
|
Costs:
|
||||||
|
|
||||||
|
1. browser-based login may not work with all MCP clients
|
||||||
|
2. non-browser MCP clients may need Cloudflare Access service tokens
|
||||||
|
3. adds operational configuration for a low-sensitivity endpoint
|
||||||
|
|
||||||
|
### Using mTLS
|
||||||
|
|
||||||
|
mTLS is useful when both client and server environments are tightly controlled.
|
||||||
|
|
||||||
|
Benefits:
|
||||||
|
|
||||||
|
1. strong client identity
|
||||||
|
2. good fit for service-to-service or private infrastructure
|
||||||
|
3. can be used between Cloudflare, Caddy, and the backend if desired
|
||||||
|
|
||||||
|
Costs:
|
||||||
|
|
||||||
|
1. harder certificate provisioning and rotation
|
||||||
|
2. weaker compatibility with normal MCP clients
|
||||||
|
3. unnecessary for public documentation-only content
|
||||||
|
|
||||||
|
For this project, mTLS is not the primary recommendation.
|
||||||
|
|
||||||
|
## Practical Recommendation
|
||||||
|
|
||||||
|
Use a simple public-docs posture unless the endpoint changes.
|
||||||
|
|
||||||
|
Recommended current setup:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/docs public
|
||||||
|
/mcp public or lightly protected
|
||||||
|
```
|
||||||
|
|
||||||
|
If `/mcp` remains public, add only basic operational safeguards:
|
||||||
|
|
||||||
|
1. keep Cloudflare Tunnel and Caddy in front
|
||||||
|
2. avoid publishing `8765` directly
|
||||||
|
3. enable Cloudflare or Caddy rate limiting if traffic becomes noisy
|
||||||
|
4. monitor logs for unusual request volume
|
||||||
|
5. document that MCP resources must remain safe to publish
|
||||||
|
|
||||||
|
A slightly stricter setup is also reasonable:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/docs public
|
||||||
|
/mcp Cloudflare Access or service token
|
||||||
|
```
|
||||||
|
|
||||||
|
This is the best option if the team wants to reduce drive-by MCP traffic without adding auth code to the application.
|
||||||
|
|
||||||
|
## Upgrade Trigger
|
||||||
|
|
||||||
|
Add real authentication before introducing any MCP capability that can:
|
||||||
|
|
||||||
|
1. read non-public files
|
||||||
|
2. access private notes or credentials
|
||||||
|
3. call upstream APIs
|
||||||
|
4. mutate data
|
||||||
|
5. run commands
|
||||||
|
6. expose environment details
|
||||||
|
7. perform expensive computation
|
||||||
|
|
||||||
|
At that point, prefer edge-level authentication first, such as Cloudflare Access, and consider proper OAuth 2.1 resource-server behavior only if broad public MCP client interoperability becomes a goal.
|
||||||
|
|
||||||
|
## Security Invariant
|
||||||
|
|
||||||
|
Everything exposed by the MCP server must be safe to publish publicly.
|
||||||
|
|
||||||
|
If that invariant stops being true, `/mcp` should be protected before the new capability is deployed.
|
||||||
+50
-24
@@ -1,6 +1,21 @@
|
|||||||
---
|
---
|
||||||
name: async-fastapi-sqlmodel
|
name: async-fastapi-sqlmodel
|
||||||
description: 'Explain and apply async database principles for FastAPI, SQLAlchemy 2.x, and SQLModel. Use when: learning or reviewing cached AsyncEngine and session-factory lifecycles, AsyncSession scopes and injection, FastAPI lifespan and yield dependencies, transaction boundaries, concurrency safety, implicit ORM I/O, pooling, testing, or SQLModel integration.'
|
description: 'Explain and apply async database principles for FastAPI, SQLAlchemy 2.x, and SQLModel. Use when: learning or reviewing AsyncEngine and AsyncSession lifecycles, FastAPI lifespan and yield dependencies, transaction boundaries, concurrency safety, implicit ORM I/O, AsyncExitStack, pooling, testing, or SQLModel integration.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: async-fastapi-sqlmodel
|
||||||
|
version: 1.1.0
|
||||||
|
tags:
|
||||||
|
- fastapi
|
||||||
|
- sqlalchemy
|
||||||
|
- sqlmodel
|
||||||
|
- async
|
||||||
|
- asyncio
|
||||||
|
- database
|
||||||
|
- transactions
|
||||||
|
- resource-lifecycle
|
||||||
|
- architecture
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/async-fastapi-sqlmodel/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# Async FastAPI, SQLAlchemy, and SQLModel
|
# Async FastAPI, SQLAlchemy, and SQLModel
|
||||||
@@ -9,8 +24,6 @@ Use this skill to explain how an async database layer works, why the recommended
|
|||||||
|
|
||||||
Primary targets: PostgreSQL with asyncpg and SQLite with aiosqlite.
|
Primary targets: PostgreSQL with asyncpg and SQLite with aiosqlite.
|
||||||
|
|
||||||
Engine and session mechanics mirror the [`nicegui-db` template repository](https://forgejo.john-stream.com/john/nicegui-db). Treat that template as the implementation baseline, then explain the rationale, lifecycle constraints, and tradeoffs behind its cached engines, session factories, context managers, dependency wiring, and `with_session` decorator. Source-specific claims in the references link to the reviewed template commit so behavior remains auditable as the template evolves.
|
|
||||||
|
|
||||||
## When to Use
|
## When to Use
|
||||||
|
|
||||||
- Explain an async engine, session factory, session, connection, or transaction.
|
- Explain an async engine, session factory, session, connection, or transaction.
|
||||||
@@ -38,7 +51,7 @@ Keep three ownership scopes distinct:
|
|||||||
|
|
||||||
| Scope | Object | Purpose | Typical owner |
|
| Scope | Object | Purpose | Typical owner |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| Application process | Cached `AsyncEngine` and lifespan-owned `async_sessionmaker` | Dialect, connection pool, schema initialization, and repeatable session configuration | FastAPI lifespan |
|
| Application process | `AsyncEngine` and `async_sessionmaker` | Dialect, connection pool, and repeatable session configuration | FastAPI lifespan |
|
||||||
| Request or concurrent task | `AsyncSession` | Mutable ORM identity map and transactional state | A `yield` dependency or explicit unit of work |
|
| Request or concurrent task | `AsyncSession` | Mutable ORM identity map and transactional state | A `yield` dependency or explicit unit of work |
|
||||||
| Atomic operation | `SessionTransaction` | Commit all changes together or roll them back together | Service or use-case boundary |
|
| Atomic operation | `SessionTransaction` | Commit all changes together or roll them back together | Service or use-case boundary |
|
||||||
|
|
||||||
@@ -48,16 +61,16 @@ The engine is a long-lived factory and pool, not a single database connection. T
|
|||||||
|
|
||||||
### Match lifetime to ownership
|
### Match lifetime to ownership
|
||||||
|
|
||||||
- Resolve one cached `AsyncEngine` per database URL during the active application lifecycle.
|
- Create one `AsyncEngine` per process and database configuration in the normal case.
|
||||||
- Enter one owning engine scope per URL; initialize registered SQLModel metadata by default, then dispose the engine and clear cached resolution on exit.
|
- Dispose it explicitly in an awaitable shutdown path; garbage collection cannot reliably await async driver cleanup.
|
||||||
- Configure the application `async_sessionmaker` inside the engine lifecycle; use the template's cached factory resolver only for standalone helpers that cannot receive the application factory.
|
- Configure `async_sessionmaker` once and call it to create short-lived sessions.
|
||||||
- Close each session deterministically with `async with` or a FastAPI dependency that yields once.
|
- Close each session deterministically with `async with` or a FastAPI dependency that yields once.
|
||||||
|
|
||||||
See [engine lifecycle](references/engine.md) and [session management](references/session.md).
|
See [engine lifecycle](references/engine.md) and [session management](references/session.md).
|
||||||
|
|
||||||
### Isolate mutable session state
|
### Isolate mutable session state
|
||||||
|
|
||||||
An `AsyncSession` represents one stateful transaction in progress. Never use one session in multiple concurrent tasks, including branches of `asyncio.gather()`. Give each task its own session. Template-style `@with_session` functions inject one only when the `session` argument is omitted; a supplied session remains caller-owned, and explicit `None` is forwarded unchanged.
|
An `AsyncSession` represents one stateful transaction in progress. Never use one session in multiple concurrent tasks, including branches of `asyncio.gather()`. Give each task its own session and pass sessions explicitly rather than relying on mutable scoped globals.
|
||||||
|
|
||||||
See [session management](references/session.md).
|
See [session management](references/session.md).
|
||||||
|
|
||||||
@@ -79,9 +92,9 @@ See [transaction boundaries](references/transactions.md).
|
|||||||
|
|
||||||
FastAPI lifespan owns resources shared by many requests. A dependency with one `yield` owns request-scoped resources and runs cleanup after use. These are related context-manager mechanisms but solve different lifetime problems.
|
FastAPI lifespan owns resources shared by many requests. A dependency with one `yield` owns request-scoped resources and runs cleanup after use. These are related context-manager mechanisms but solve different lifetime problems.
|
||||||
|
|
||||||
Use `AsyncExitStack` when lifespan acquires a variable, conditional, or mixed collection of context-managed resources. It records cleanup as resources are acquired and unwinds callbacks in reverse order. A single engine should use the direct engine context manager; `AsyncExitStack` is a composition tool, not a requirement.
|
Use `AsyncExitStack` when lifespan acquires a variable, conditional, or mixed collection of context-managed resources. It records cleanup as resources are acquired and unwinds callbacks in reverse order. A single engine with one cleanup callback can use a plain `try/finally`; `AsyncExitStack` is a composition tool, not a requirement.
|
||||||
|
|
||||||
See [FastAPI database integration](references/fastapi.md).
|
See [engine lifecycle](references/engine.md).
|
||||||
|
|
||||||
### Use SQLModel as the primary modeling layer
|
### Use SQLModel as the primary modeling layer
|
||||||
|
|
||||||
@@ -97,14 +110,6 @@ Pool sizing, overflow, recycle, pre-ping, isolation, statement timeouts, and hea
|
|||||||
|
|
||||||
See [observability and resilience](references/observability.md).
|
See [observability and resilience](references/observability.md).
|
||||||
|
|
||||||
### Test through the production seam
|
|
||||||
|
|
||||||
Keep the production engine and session-factory construction path intact in tests. Select a dedicated PostgreSQL, local SQLite, or in-memory SQLite URL at that seam, then override the request-session dependency only for the test lifetime. Use a test-scoped outer transaction with SAVEPOINT-backed session commits when application code calls `commit()`; it exercises normal transaction behavior while cleanup remains deterministic.
|
|
||||||
|
|
||||||
In-memory SQLite is suitable for serial tests. For multiple simultaneous sessions, use a named shared-cache SQLite URL or a temporary file, and retain PostgreSQL integration coverage for PostgreSQL-specific behavior.
|
|
||||||
|
|
||||||
See [database testing and fixture data](references/testing.md).
|
|
||||||
|
|
||||||
## Reference Map
|
## Reference Map
|
||||||
|
|
||||||
| Concept | Reference |
|
| Concept | Reference |
|
||||||
@@ -112,19 +117,41 @@ See [database testing and fixture data](references/testing.md).
|
|||||||
| Engine lifecycle and ownership | [Engine lifecycle reference](references/engine.md) |
|
| Engine lifecycle and ownership | [Engine lifecycle reference](references/engine.md) |
|
||||||
| Session factory and scope | [Session management reference](references/session.md) |
|
| Session factory and scope | [Session management reference](references/session.md) |
|
||||||
| Transaction boundaries | [Transaction boundaries reference](references/transactions.md) |
|
| Transaction boundaries | [Transaction boundaries reference](references/transactions.md) |
|
||||||
| FastAPI lifespan composition | [FastAPI integration reference](references/fastapi.md) |
|
| Lifespan composition | [Engine lifecycle reference](references/engine.md) |
|
||||||
| FastAPI dependency injection | [FastAPI integration reference](references/fastapi.md) |
|
| Dependency injection | [Session management reference](references/session.md) |
|
||||||
| Implicit I/O control in ORM | [Implicit I/O reference](references/implicit_io.md) |
|
| Implicit I/O control in ORM | [Implicit I/O reference](references/implicit_io.md) |
|
||||||
| Observability and resilience | [Observability reference](references/observability.md) |
|
| Observability and resilience | [Observability reference](references/observability.md) |
|
||||||
| SQLModel-first modeling | [SQLModel integration reference](references/sqlmodel.md) |
|
| SQLModel-first modeling | [SQLModel integration reference](references/sqlmodel.md) |
|
||||||
| CRUD repository and standalone functions | [Basic CRUD reference](references/crud.md) |
|
| CRUD repository and standalone functions | [Basic CRUD reference](references/crud.md) |
|
||||||
| Test database selection and fixture data | [Database testing reference](references/testing.md) |
|
|
||||||
|
|
||||||
## Canonical Composition Pattern
|
## Canonical Composition Pattern
|
||||||
|
|
||||||
The framework-independent primitives live in [engine lifecycle](references/engine.md), [session management](references/session.md), and [transaction boundaries](references/transactions.md). Their canonical FastAPI adaptation, including lifespan state and `Annotated` dependencies, lives in [FastAPI database integration](references/fastapi.md).
|
This example shows the ownership boundaries. Adapt state storage and dependency wiring to the application's conventions.
|
||||||
|
|
||||||
For background work that outlives a request, inject the shared factory and create a new session inside that task instead of retaining the request's session.
|
```python
|
||||||
|
from contextlib import AsyncExitStack, asynccontextmanager
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
async with AsyncExitStack() as stack:
|
||||||
|
engine = create_async_engine(settings.database_url)
|
||||||
|
stack.push_async_callback(engine.dispose)
|
||||||
|
|
||||||
|
session_factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||||
|
app.state.session_factory = session_factory
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
async def get_session() -> AsyncIterator[AsyncSession]:
|
||||||
|
async with app.state.session_factory() as session:
|
||||||
|
yield session
|
||||||
|
```
|
||||||
|
|
||||||
|
For direct construction without `AsyncExitStack`, put `await engine.dispose()` in a `finally` block. For background work that outlives a request, create a new session inside that task instead of retaining the request's session.
|
||||||
|
|
||||||
## Explanation Procedure
|
## Explanation Procedure
|
||||||
|
|
||||||
@@ -146,7 +173,6 @@ When reviewing code, verify:
|
|||||||
- Relationship and deferred-column access cannot surprise the event loop with implicit I/O.
|
- Relationship and deferred-column access cannot surprise the event loop with implicit I/O.
|
||||||
- Pool and timeout settings are justified by deployment behavior.
|
- Pool and timeout settings are justified by deployment behavior.
|
||||||
- Tests exercise rollback, cleanup, concurrency, and lifespan behavior where relevant.
|
- Tests exercise rollback, cleanup, concurrency, and lifespan behavior where relevant.
|
||||||
- Tests use a dedicated database target and preserve production session mechanics.
|
|
||||||
|
|
||||||
## Anti-Patterns to Flag
|
## Anti-Patterns to Flag
|
||||||
|
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
# Basic CRUD Repository and Functions
|
||||||
|
|
||||||
|
!!! info "Primary sources"
|
||||||
|
- [SQLModel create-data tutorial](https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/)
|
||||||
|
- [SQLModel update-data tutorial](https://sqlmodel.tiangolo.com/tutorial/fastapi/update-extra-data/)
|
||||||
|
- [SQLModel select tutorial](https://sqlmodel.tiangolo.com/tutorial/select/)
|
||||||
|
- [SQLAlchemy `AsyncSession` API](https://docs.sqlalchemy.org/en/21/orm/extensions/asyncio.html#sqlalchemy.ext.asyncio.AsyncSession)
|
||||||
|
|
||||||
|
??? abstract "Decision metadata"
|
||||||
|
- Status: adopted
|
||||||
|
- Decision level: advisory
|
||||||
|
- Applies to: api-runtime, workers, tests
|
||||||
|
- Last reviewed: 2026-07-26
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Show a small SQLModel CRUD layer in two forms:
|
||||||
|
|
||||||
|
- independent functions for convenient standalone or composed operations;
|
||||||
|
- a repository object that groups those functions behind one domain-oriented interface.
|
||||||
|
|
||||||
|
Every public operation accepts an optional `AsyncSession`. When omitted, reads resolve the cached session factory and own a short-lived session, while writes resolve the same factory and own a complete session-and-transaction scope. When supplied, reads borrow the session and writes borrow its already-active caller-owned transaction. The repository stores configuration and delegates to the same functions without changing those semantics.
|
||||||
|
|
||||||
|
Use the same vocabulary at every layer:
|
||||||
|
|
||||||
|
| Operation | Function | Repository method | Scope when session is omitted | Missing-row result |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Create | `create_widget()` | `create()` | Owned transaction | Not applicable |
|
||||||
|
| Read one | `get_widget()` | `get()` | Owned session | `None` |
|
||||||
|
| Read many | `list_widgets()` | `list()` | Owned session | Empty list |
|
||||||
|
| Update | `update_widget()` | `update()` | Owned transaction | `None` |
|
||||||
|
| Delete | `delete_widget()` | `delete()` | Owned transaction | `None` |
|
||||||
|
|
||||||
|
Functions and repository methods both put domain arguments first. Database configuration and sessions are keyword-only infrastructure arguments. This keeps call sites analogous and makes ownership choices visible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Models
|
||||||
|
|
||||||
|
Start with one table model when the application does not need distinct persistence and API schemas.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sqlmodel import Field
|
||||||
|
from sqlmodel import SQLModel
|
||||||
|
|
||||||
|
|
||||||
|
class Widget(SQLModel, table=True):
|
||||||
|
id: int | None = Field(default=None, primary_key=True)
|
||||||
|
name: str = Field(index=True)
|
||||||
|
description: str | None = None
|
||||||
|
```
|
||||||
|
|
||||||
|
This reference uses direct field arguments and full-update semantics to keep the CRUD mechanics visible. Introduce separate create, update, or public schemas only when an API boundary needs different validation, field visibility, or partial-update behavior. See [SQLModel integration](sqlmodel.md) for that larger modeling pattern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Independent CRUD Functions
|
||||||
|
|
||||||
|
Functions are the simplest default when grouping state or behavior in an object adds no value. Each function is a complete operation boundary: it can run standalone by resolving the cached factory from `database_url`, or compose into a caller-owned scope through `session`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlmodel import select
|
||||||
|
|
||||||
|
from .session import session_scope
|
||||||
|
from .session import transaction_scope
|
||||||
|
|
||||||
|
|
||||||
|
async def create_widget(
|
||||||
|
name: str,
|
||||||
|
description: str | None = None,
|
||||||
|
*,
|
||||||
|
database_url: str,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget:
|
||||||
|
async with transaction_scope(
|
||||||
|
database_url=database_url,
|
||||||
|
session=session,
|
||||||
|
) as active_session:
|
||||||
|
widget = Widget(name=name, description=description)
|
||||||
|
active_session.add(widget)
|
||||||
|
await active_session.flush()
|
||||||
|
return widget
|
||||||
|
|
||||||
|
|
||||||
|
async def get_widget(
|
||||||
|
widget_id: int,
|
||||||
|
*,
|
||||||
|
database_url: str,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget | None:
|
||||||
|
async with session_scope(
|
||||||
|
database_url=database_url,
|
||||||
|
session=session,
|
||||||
|
) as active_session:
|
||||||
|
return await active_session.get(Widget, widget_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def list_widgets(
|
||||||
|
*,
|
||||||
|
database_url: str,
|
||||||
|
offset: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> list[Widget]:
|
||||||
|
if offset < 0:
|
||||||
|
raise ValueError("offset must be non-negative")
|
||||||
|
if not 1 <= limit <= 100:
|
||||||
|
raise ValueError("limit must be between 1 and 100")
|
||||||
|
|
||||||
|
async with session_scope(
|
||||||
|
database_url=database_url,
|
||||||
|
session=session,
|
||||||
|
) as active_session:
|
||||||
|
statement = select(Widget).order_by(Widget.id).offset(offset).limit(limit)
|
||||||
|
return list(await active_session.scalars(statement))
|
||||||
|
|
||||||
|
|
||||||
|
async def update_widget(
|
||||||
|
widget_id: int,
|
||||||
|
name: str,
|
||||||
|
description: str | None,
|
||||||
|
*,
|
||||||
|
database_url: str,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget | None:
|
||||||
|
async with transaction_scope(
|
||||||
|
database_url=database_url,
|
||||||
|
session=session,
|
||||||
|
) as active_session:
|
||||||
|
widget = await active_session.get(Widget, widget_id)
|
||||||
|
if widget is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
widget.name = name
|
||||||
|
widget.description = description
|
||||||
|
await active_session.flush()
|
||||||
|
return widget
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_widget(
|
||||||
|
widget_id: int,
|
||||||
|
*,
|
||||||
|
database_url: str,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget | None:
|
||||||
|
async with transaction_scope(
|
||||||
|
database_url=database_url,
|
||||||
|
session=session,
|
||||||
|
) as active_session:
|
||||||
|
widget = await active_session.get(Widget, widget_id)
|
||||||
|
if widget is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
await active_session.delete(widget)
|
||||||
|
await active_session.flush()
|
||||||
|
return widget
|
||||||
|
```
|
||||||
|
|
||||||
|
Update and delete load the row through the same session that mutates it. This avoids accepting detached instances from an earlier standalone read and gives both operations an explicit `None` result that the application layer can map to a domain or HTTP error. Delete returns the loaded object for callers that need its values, but that object represents a row scheduled for deletion and must not be reused as persistent state. List operations validate their bounds and order by the primary key so pagination is deterministic. Add a unique tiebreaker whenever ordering by a non-unique field.
|
||||||
|
|
||||||
|
`flush()` sends pending writes and populates ordinary generated primary keys. It does not itself commit. For a standalone write, the surrounding owned `transaction_scope()` commits after the function body succeeds. For a supplied session, the caller's outer transaction retains commit and rollback ownership. Use `await active_session.refresh(widget)` only when the operation deliberately needs database-generated state that was not returned during the flush; an unconditional refresh adds another query.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Repository Object
|
||||||
|
|
||||||
|
A repository can provide a stable domain-facing interface when several callers need the same grouped operations. It stores repeatable database configuration, never a mutable session. Every method delegates to the analogous function and exposes the same optional-session contract.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
class WidgetRepository:
|
||||||
|
def __init__(self, database_url: str) -> None:
|
||||||
|
self.database_url = database_url
|
||||||
|
|
||||||
|
async def create(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
description: str | None = None,
|
||||||
|
*,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget:
|
||||||
|
return await create_widget(
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
database_url=self.database_url,
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def get(
|
||||||
|
self,
|
||||||
|
widget_id: int,
|
||||||
|
*,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget | None:
|
||||||
|
return await get_widget(
|
||||||
|
widget_id,
|
||||||
|
database_url=self.database_url,
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def list(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
offset: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> list[Widget]:
|
||||||
|
return await list_widgets(
|
||||||
|
database_url=self.database_url,
|
||||||
|
offset=offset,
|
||||||
|
limit=limit,
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def update(
|
||||||
|
self,
|
||||||
|
widget_id: int,
|
||||||
|
name: str,
|
||||||
|
description: str | None,
|
||||||
|
*,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget | None:
|
||||||
|
return await update_widget(
|
||||||
|
widget_id,
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
database_url=self.database_url,
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def delete(
|
||||||
|
self,
|
||||||
|
widget_id: int,
|
||||||
|
*,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget | None:
|
||||||
|
return await delete_widget(
|
||||||
|
widget_id,
|
||||||
|
database_url=self.database_url,
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
The object is intentionally thin. Tests can construct it with a test database URL or pass a transaction-scoped test session to individual methods. A caller-provided session always wins and remains open after the method returns. A standalone operation closes its owned session before returning, so returned objects are detached; load every required scalar, deferred column, and relationship explicitly before the scope exits, and do not mutate those objects expecting persistence.
|
||||||
|
|
||||||
|
If a read participates in a later write, pass the same session and place both operations inside the explicit transaction. This avoids splitting one use case across sessions and keeps SQLAlchemy's autobegin behavior from obscuring transaction ownership. Add a repository only when its naming, shared query policy, dependency substitution, or domain boundary improves the application. Independent functions remain a valid and often clearer design.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Transaction Ownership
|
||||||
|
|
||||||
|
Compose multiple calls under one use-case transaction. At this boundary, a supplied session joins its already-active caller-owned transaction, while omitting the session creates a standalone session and transaction. Each nested CRUD write receives `active_session`, detects that transaction, and borrows it instead of committing independently.
|
||||||
|
|
||||||
|
The scope names describe exactly what they own: `session_scope()` manages session lifetime but never commits, while `transaction_scope()` manages a complete transaction only when it also creates the session. Both yield the name `active_session` because downstream CRUD code does not need to know whether the session was borrowed or owned.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from .session import transaction_scope
|
||||||
|
|
||||||
|
|
||||||
|
async def replace_widget(
|
||||||
|
repository: WidgetRepository,
|
||||||
|
widget_id: int,
|
||||||
|
replacement_name: str,
|
||||||
|
replacement_description: str | None = None,
|
||||||
|
*,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Widget | None:
|
||||||
|
async with transaction_scope(
|
||||||
|
database_url=repository.database_url,
|
||||||
|
session=session,
|
||||||
|
) as active_session:
|
||||||
|
deleted_widget = await repository.delete(
|
||||||
|
widget_id,
|
||||||
|
session=active_session,
|
||||||
|
)
|
||||||
|
if deleted_widget is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return await repository.create(
|
||||||
|
replacement_name,
|
||||||
|
replacement_description,
|
||||||
|
session=active_session,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
If creation fails, deletion rolls back with it. For a caller-owned transaction, wrap the call in `async with session.begin():` and pass that session. For a standalone use case, omit the session; the outer `transaction_scope()` commits on successful exit, rolls back on exception, and closes its owned session. Do not add direct `commit()` calls to CRUD functions or repository methods because that prevents callers from composing several operations atomically. See [transaction boundaries](transactions.md) and [session management](session.md) for ownership details.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anti-Patterns
|
||||||
|
|
||||||
|
- Storing one mutable `AsyncSession` on a long-lived repository object.
|
||||||
|
- Constructing ad hoc factories or sessions instead of resolving the cached factory through the scope helpers.
|
||||||
|
- Using `session_scope()` for an optional write, which would close an owned session without committing.
|
||||||
|
- Accepting a supplied session for a write without requiring an active caller-owned transaction.
|
||||||
|
- Calling `commit()` or `rollback()` directly instead of expressing ownership through `transaction_scope()`.
|
||||||
|
- Accepting unbounded list queries.
|
||||||
|
- Accepting detached ORM instances for update or delete when an identifier can be resolved in the active session.
|
||||||
|
- Accessing unloaded attributes after a standalone repository read has closed its owned session.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Operational Checks
|
||||||
|
|
||||||
|
- Every CRUD call receives a task-local `AsyncSession`.
|
||||||
|
- Standalone reads resolve the cached factory by database URL and close their owned session.
|
||||||
|
- Standalone writes resolve the cached factory and own commit, rollback, and session cleanup through `transaction_scope()`.
|
||||||
|
- Supplied write sessions already have an active caller-owned transaction.
|
||||||
|
- Each complete operation, service, or use-case boundary borrows an active transaction or owns a complete session-and-transaction scope.
|
||||||
|
- List operations have pagination and deterministic ordering where required.
|
||||||
|
- Update requires values for both mutable fields; passing `None` explicitly clears the nullable description.
|
||||||
|
- Get, update, and delete use the same identifier and missing-row semantics.
|
||||||
|
- Functions and repository methods use domain arguments first and keyword-only infrastructure arguments consistently.
|
||||||
|
- Standalone reads load all state needed after their owned session closes.
|
||||||
|
- Repository objects hold configuration or policy, never request-scoped session state.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing Checks
|
||||||
|
|
||||||
|
- Create tests verify generated identifiers and persisted field values after commit.
|
||||||
|
- Get and list tests cover found, missing, pagination, and ordering behavior.
|
||||||
|
- List tests reject negative offsets and limits outside the supported range.
|
||||||
|
- Update tests cover replacement of both mutable fields, including clearing the nullable description.
|
||||||
|
- Update and delete tests cover missing identifiers without mutating the database.
|
||||||
|
- Delete tests verify the returned row and its absence after commit.
|
||||||
|
- Failure tests verify that a surrounding transaction rolls back all composed CRUD calls.
|
||||||
|
- Optional-session read tests verify borrowed sessions remain open and owned sessions close without committing.
|
||||||
|
- Optional-session write tests verify supplied transactions remain caller-owned and standalone transactions commit or roll back before closing.
|
||||||
|
- Composition tests pass one active session through several CRUD calls and verify one atomic commit or rollback.
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# Async SQLAlchemy Engine
|
||||||
|
|
||||||
|
!!! info "Primary sources"
|
||||||
|
- [Python `functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache)
|
||||||
|
- [SQLAlchemy connections](https://docs.sqlalchemy.org/en/21/core/connections.html)
|
||||||
|
- [SQLAlchemy asyncio extension](https://docs.sqlalchemy.org/en/21/orm/extensions/asyncio.html)
|
||||||
|
- [SQLAlchemy pooling and multiprocessing](https://docs.sqlalchemy.org/en/21/core/pooling.html#pooling-multiprocessing)
|
||||||
|
- [FastAPI lifespan events](https://fastapi.tiangolo.com/advanced/events/)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Engine Ownership Model
|
||||||
|
|
||||||
|
Create one async engine per process per database URL and keep engine construction independent from FastAPI.
|
||||||
|
|
||||||
|
- SQLAlchemy guidance: the engine is intended as a long-lived, concurrent registry over pooled DB connections, not a per-request object.
|
||||||
|
- A cached function provides stable process-local engine identity without making framework state the only way to obtain it.
|
||||||
|
- FastAPI lifespan starts and stops that independently defined resource; it does not contain the construction policy.
|
||||||
|
|
||||||
|
!!! tip "Practical rule"
|
||||||
|
- Exactly one `create_async_engine(...)` call in the cached engine factory.
|
||||||
|
- Zero `create_async_engine(...)` calls in request handlers.
|
||||||
|
- Zero calls to the cached factory from repository code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cached Engine Factory
|
||||||
|
|
||||||
|
Use [`functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache) on a synchronous factory. Creating an `AsyncEngine` configures the dialect and pool; it does not need to await a database connection.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from functools import cache
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def get_engine(database_url: str) -> AsyncEngine:
|
||||||
|
return create_async_engine(
|
||||||
|
database_url,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def dispose_engine(database_url: str) -> None:
|
||||||
|
engine = get_engine(database_url)
|
||||||
|
try:
|
||||||
|
await engine.dispose()
|
||||||
|
finally:
|
||||||
|
get_engine.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
async def refresh_engine(database_url: str) -> AsyncEngine:
|
||||||
|
await dispose_engine(database_url)
|
||||||
|
return get_engine(database_url)
|
||||||
|
```
|
||||||
|
|
||||||
|
The database URL is an explicit, hashable cache key. Calls with the same URL return the same engine; a different URL receives a different engine. If engine options vary at runtime, make them explicit hashable arguments too.
|
||||||
|
|
||||||
|
Resolve settings at the composition boundary and call `get_engine(settings.database_url)`. Do not hide settings lookup or engine creation inside feature code.
|
||||||
|
|
||||||
|
## Thin FastAPI Lifespan Wrapper
|
||||||
|
|
||||||
|
The lifespan context manager only connects the cached resource to FastAPI ownership:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
database_url = app.state.settings.database_url
|
||||||
|
engine = get_engine(database_url)
|
||||||
|
app.state.engine = engine
|
||||||
|
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
await dispose_engine(database_url)
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
```
|
||||||
|
|
||||||
|
`dispose()` closes checked-in connections and replaces the pool, but it does not remove the Python object from `functools.cache`. `dispose_engine()` clears the cache even if driver cleanup raises, preventing a later lifespan run or test from retrieving that engine instance.
|
||||||
|
|
||||||
|
This simple cleanup assumes one configured database URL per process. If a process intentionally owns several cached engines, use a small registry with per-key removal instead of clearing the whole cache. For a fixed engine, `try/finally` is sufficient; use `AsyncExitStack` when lifespan composes multiple conditional or dynamically acquired resources.
|
||||||
|
|
||||||
|
When directly testing engine construction or lifespan behavior:
|
||||||
|
|
||||||
|
- Call `get_engine.cache_clear()` before the test to remove process-local state.
|
||||||
|
- Dispose any engine the test creates.
|
||||||
|
- Clear the cache again during teardown, even when the test fails.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Driver URLs (Project Requirement: asyncpg + aiosqlite)
|
||||||
|
|
||||||
|
Use SQLAlchemy async driver URLs:
|
||||||
|
|
||||||
|
- PostgreSQL: `postgresql+asyncpg://user:pass@host:5432/dbname`
|
||||||
|
- SQLite: `sqlite+aiosqlite:///./app.db`
|
||||||
|
|
||||||
|
!!! warning "Driver compatibility"
|
||||||
|
- Do not mix sync drivers, for example `psycopg2`, with `create_async_engine()`.
|
||||||
|
- Keep URL construction centralized in settings/config, not in feature modules.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pooling Defaults and Tuning
|
||||||
|
|
||||||
|
Default behavior is usually correct first:
|
||||||
|
|
||||||
|
- Async engines use async-compatible pooling (`AsyncAdaptedQueuePool`) by default.
|
||||||
|
- Start with defaults, then tune from observed load (`pool_size`, `max_overflow`, `pool_timeout`, `pool_recycle`).
|
||||||
|
- Enable `pool_pre_ping=True` for safer stale-connection handling in long-running services.
|
||||||
|
|
||||||
|
When to switch pool strategy:
|
||||||
|
|
||||||
|
- `NullPool` if you explicitly need no pooling (special environments, some tests, or strict cross-loop constraints).
|
||||||
|
- Keep in mind this increases connect/disconnect churn.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Disposal Semantics
|
||||||
|
|
||||||
|
`engine.dispose()` replaces/disposes the pool, but only checked-in connections are immediately closed.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
- Dispose when the app is shutting down.
|
||||||
|
- Dispose before reusing an engine across event loops.
|
||||||
|
- In forked child-process initialization, use `engine.dispose(close=False)` (sync API guidance) so child processes do not touch parent-held connections.
|
||||||
|
|
||||||
|
Avoid relying on garbage collection for engine cleanup in async code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Event Loop and Process Boundaries
|
||||||
|
|
||||||
|
Do not share pooled connections across boundaries:
|
||||||
|
|
||||||
|
- Multiple event loops: do not reuse the same pooled async engine across loops unless you intentionally disable pooling (`NullPool`) or dispose before handoff.
|
||||||
|
- Multiprocessing/fork: pooled connections must not be inherited for active use across process boundaries.
|
||||||
|
|
||||||
|
This prevents broken socket state and cross-process connection corruption.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What Not to Do
|
||||||
|
|
||||||
|
- Create an engine inside every request dependency.
|
||||||
|
- Create/dispose engines inside repository methods.
|
||||||
|
- Call `get_engine()` from repositories instead of injecting their engine or session dependency.
|
||||||
|
- Keep engine creation as a hidden side effect of import-time module globals.
|
||||||
|
- Dispose a cached engine without clearing the cache during final teardown.
|
||||||
|
- Use deprecated FastAPI startup/shutdown events together with lifespan.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Engine Design Checklist
|
||||||
|
|
||||||
|
- One engine per process per DB URL.
|
||||||
|
- Engine created by one cached, framework-independent factory.
|
||||||
|
- Lifespan only retrieves, exposes, disposes, and uncaches the engine.
|
||||||
|
- Async driver URL matches backend (`asyncpg` or `aiosqlite`).
|
||||||
|
- Pooling strategy is explicit for non-default needs.
|
||||||
|
- No request-path engine creation.
|
||||||
|
- Tests dispose engines and clear cached state deterministically.
|
||||||
+4
-6
@@ -8,15 +8,13 @@ Purpose: concept registry for the principles, mechanics, and implementation guid
|
|||||||
|
|
||||||
| Concept | File | Status | Decision Level | Owner | Last Reviewed |
|
| Concept | File | Status | Decision Level | Owner | Last Reviewed |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| Engine lifecycle and ownership | [engine.md](engine.md) | adopted | mandatory | platform/backend | 2026-08-06 |
|
| Engine lifecycle and ownership | [engine.md](engine.md) | adopted | mandatory | platform/backend | 2026-06-17 |
|
||||||
| Session factory and scope | [session.md](session.md) | adopted | mandatory | platform/backend | 2026-08-06 |
|
| Session factory and scope | [session.md](session.md) | adopted | mandatory | platform/backend | 2026-06-17 |
|
||||||
| FastAPI lifespan and dependency injection | [fastapi.md](fastapi.md) | adopted | mandatory | platform/backend | 2026-08-06 |
|
|
||||||
| Transaction boundaries | [transactions.md](transactions.md) | adopted | mandatory | platform/backend | 2026-06-17 |
|
| Transaction boundaries | [transactions.md](transactions.md) | adopted | mandatory | platform/backend | 2026-06-17 |
|
||||||
| Implicit ORM I/O under asyncio | [implicit_io.md](implicit_io.md) | adopted | advisory | platform/backend | 2026-06-17 |
|
| Implicit ORM I/O under asyncio | [implicit_io.md](implicit_io.md) | adopted | advisory | platform/backend | 2026-06-17 |
|
||||||
| Observability and resilience | [observability.md](observability.md) | adopted | mandatory | platform/backend | 2026-06-17 |
|
| Observability and resilience | [observability.md](observability.md) | adopted | mandatory | platform/backend | 2026-06-17 |
|
||||||
| SQLModel modeling and async boundaries | [sqlmodel.md](sqlmodel.md) | adopted | mandatory | platform/backend | 2026-08-06 |
|
| SQLModel modeling and async boundaries | [sqlmodel.md](sqlmodel.md) | adopted | mandatory | platform/backend | 2026-07-26 |
|
||||||
| Basic CRUD repository and functions | [crud.md](crud.md) | adopted | advisory | platform/backend | 2026-08-06 |
|
| Basic CRUD repository and functions | [crud.md](crud.md) | adopted | advisory | platform/backend | 2026-07-26 |
|
||||||
| Test database targets and fixture data | [testing.md](testing.md) | adopted | mandatory | platform/backend | 2026-08-06 |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
# Async SQLAlchemy Session Management
|
||||||
|
|
||||||
|
!!! info "Primary sources"
|
||||||
|
- [Python `functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache)
|
||||||
|
- [Python `asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
|
||||||
|
- [SQLAlchemy asyncio extension](https://docs.sqlalchemy.org/en/21/orm/extensions/asyncio.html)
|
||||||
|
- [SQLAlchemy session basics](https://docs.sqlalchemy.org/en/21/orm/session_basics.html)
|
||||||
|
- [FastAPI dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Define one canonical session model for FastAPI + SQLAlchemy asyncio:
|
||||||
|
|
||||||
|
- configure one shared session factory,
|
||||||
|
- create one AsyncSession per request or per unit-of-work,
|
||||||
|
- never share one AsyncSession across concurrent tasks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scope and Non-Goals
|
||||||
|
|
||||||
|
- In scope: session factory creation, FastAPI dependency wiring, request/task scoping, transaction demarcation.
|
||||||
|
- Out of scope: ORM model design, query optimization strategy, schema migration tooling.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- Create one cached `async_sessionmaker` per app-owned AsyncEngine.
|
||||||
|
- Let repositories resolve the cached maker by database URL.
|
||||||
|
- Use a fresh AsyncSession for each request or explicit unit-of-work.
|
||||||
|
- Pass an `AsyncSession` directly to data-access functions.
|
||||||
|
- Borrow a caller-provided session without closing or committing it.
|
||||||
|
- Do not share AsyncSession across `asyncio.gather()` or parallel tasks.
|
||||||
|
- Prefer direct dependency injection over global scoped-session patterns in new code.
|
||||||
|
- Use explicit transaction boundaries (`async with session.begin():`) for writes.
|
||||||
|
- When a use case accepts an optional session, borrow only an active caller-owned transaction or own the complete session-and-transaction scope.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Session Factory Mechanics
|
||||||
|
|
||||||
|
An `async_sessionmaker[AsyncSession]` is a reusable configuration object and callable session producer. It stores how sessions should be created, including the engine binding and options such as `expire_on_commit=False`. It is not itself a session, connection, or transaction, and calling it does not make a shared global `AsyncSession`.
|
||||||
|
|
||||||
|
Cache it by the application-owned engine so repeated composition calls return the same maker:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from functools import cache
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||||
|
|
||||||
|
from .engine import dispose_engine
|
||||||
|
from .engine import get_engine
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def get_session_factory(database_url: str) -> async_sessionmaker[AsyncSession]:
|
||||||
|
return async_sessionmaker(
|
||||||
|
bind=get_engine(database_url),
|
||||||
|
class_=AsyncSession,
|
||||||
|
expire_on_commit=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def dispose_session_factory(database_url: str) -> None:
|
||||||
|
get_session_factory.cache_clear()
|
||||||
|
await dispose_engine(database_url)
|
||||||
|
```
|
||||||
|
|
||||||
|
`functools.cache` caches by argument equality and requires hashable arguments. The database URL is an explicit string key shared with the cached engine factory. The cache retains the returned maker until `get_session_factory.cache_clear()` runs. Cache the synchronous maker function, never an async function and never a produced `AsyncSession`.
|
||||||
|
|
||||||
|
Each call to `session_factory()` creates a distinct `AsyncSession`. The caller that invokes the factory owns that session lifetime and must close it, normally with `async with`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
async with session_factory() as session:
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
The factory can be shared across requests and tasks. Sessions produced by it cannot be shared across concurrent tasks.
|
||||||
|
|
||||||
|
An `async_sessionmaker` has no connection pool or async `dispose()` method of its own. `dispose_session_factory()` means "invalidate the cached maker, then dispose its engine." Clearing the maker first ensures no subsequent composition call can retrieve a maker bound to the engine being shut down.
|
||||||
|
|
||||||
|
Use the helper when shutting down or replacing the database resources:
|
||||||
|
|
||||||
|
```python
|
||||||
|
await dispose_session_factory(database_url)
|
||||||
|
```
|
||||||
|
|
||||||
|
Otherwise, a later call can return a maker that still references the old engine object. This matters in lifespan tests, application restarts within one process, and test suites that replace engines.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Optional Session Ownership
|
||||||
|
|
||||||
|
A small [`asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager) can make repository methods composable. It borrows an existing session when supplied; otherwise it creates and closes one from a supplied factory:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def session_scope(
|
||||||
|
*,
|
||||||
|
database_url: str,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> AsyncIterator[AsyncSession]:
|
||||||
|
if session is not None:
|
||||||
|
yield session
|
||||||
|
return
|
||||||
|
|
||||||
|
async with get_session_factory(database_url)() as owned_session:
|
||||||
|
yield owned_session
|
||||||
|
```
|
||||||
|
|
||||||
|
The branch is intentionally explicit. Python's [`nullcontext`](https://docs.python.org/3/library/contextlib.html#contextlib.nullcontext) can express the same borrow-or-own idea, but the branch keeps ownership and typing obvious.
|
||||||
|
|
||||||
|
This helper manages session lifetime only:
|
||||||
|
|
||||||
|
- It does not close, commit, or roll back a supplied session; the caller owns it.
|
||||||
|
- It closes a session that it creates. Closing releases resources and rolls back an unfinished transaction; it does not commit.
|
||||||
|
- It does not start a transaction. Put `session.begin()` at the use-case boundary.
|
||||||
|
- A supplied session wins; the cached factory is not resolved.
|
||||||
|
- Otherwise, `database_url` selects the cached factory returned by `get_session_factory()`.
|
||||||
|
|
||||||
|
Do not turn this into an implicit unit-of-work helper that sometimes commits. Whether work joins an existing transaction or creates a new one must remain visible to the caller.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Optional Transaction Ownership
|
||||||
|
|
||||||
|
Use a separate context manager when a service or use-case function must support both a caller-owned transaction and a standalone transaction. A supplied session must already be inside a transaction; otherwise the helper creates a session and transaction together with `async_sessionmaker.begin()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
@asynccontextmanager
|
||||||
|
async def transaction_scope(
|
||||||
|
*,
|
||||||
|
database_url: str,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> AsyncIterator[AsyncSession]:
|
||||||
|
if session is not None:
|
||||||
|
if not session.in_transaction():
|
||||||
|
raise RuntimeError("A supplied session must have an active transaction")
|
||||||
|
yield session
|
||||||
|
return
|
||||||
|
|
||||||
|
async with get_session_factory(database_url).begin() as owned_session:
|
||||||
|
yield owned_session
|
||||||
|
```
|
||||||
|
|
||||||
|
This helper makes transaction ownership follow the same explicit borrow-or-own mechanics as session ownership:
|
||||||
|
|
||||||
|
- A supplied session and its active transaction remain caller-owned. The helper does not commit, roll back, or close them.
|
||||||
|
- Without a supplied session, the helper owns the session and transaction. Successful exit commits; exceptional exit rolls back; either path closes the session.
|
||||||
|
- Use this helper only at a complete operation, service, or use-case boundary. A public CRUD function or repository method may be such a boundary when its optional-session contract explicitly states that omitting the session owns and commits one transaction. Never use it inside a lower-level session-required helper.
|
||||||
|
- Do not silently begin a transaction on a supplied session. That would make commit ownership depend on hidden helper behavior.
|
||||||
|
|
||||||
|
Callers that supply a session make their ownership visible with an outer transaction:
|
||||||
|
|
||||||
|
```python
|
||||||
|
async with session_factory() as session:
|
||||||
|
async with session.begin():
|
||||||
|
await run_use_case(..., session=session)
|
||||||
|
```
|
||||||
|
|
||||||
|
Standalone callers omit the session and let the use case own the complete unit of work:
|
||||||
|
|
||||||
|
```python
|
||||||
|
await run_use_case(...)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Repository and Function Boundaries
|
||||||
|
|
||||||
|
Pass the database URL to repository constructors. The repository stores repeatable database configuration, not mutable session state, and `session_scope()` resolves the cached factory when a standalone operation needs a session:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
|
||||||
|
async def find_item(session: AsyncSession, item_id: int) -> Item | None:
|
||||||
|
statement = select(Item).where(Item.id == item_id)
|
||||||
|
return await session.scalar(statement)
|
||||||
|
|
||||||
|
|
||||||
|
class ItemRepository:
|
||||||
|
def __init__(self, database_url: str) -> None:
|
||||||
|
self.database_url = database_url
|
||||||
|
|
||||||
|
async def find(
|
||||||
|
self,
|
||||||
|
item_id: int,
|
||||||
|
*,
|
||||||
|
session: AsyncSession | None = None,
|
||||||
|
) -> Item | None:
|
||||||
|
async with session_scope(
|
||||||
|
database_url=self.database_url,
|
||||||
|
session=session,
|
||||||
|
) as active_session:
|
||||||
|
return await find_item(active_session, item_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
This split gives each layer one job:
|
||||||
|
|
||||||
|
- The repository object identifies its database configuration and creates a session only for a standalone call.
|
||||||
|
- Standalone calls reuse the cached factory selected by database URL.
|
||||||
|
- A caller can pass a session to join an existing unit of work; the repository borrows it.
|
||||||
|
- The access function owns only the query and requires an existing `AsyncSession`.
|
||||||
|
- Application wiring supplies the production factory.
|
||||||
|
- Tests can use a test database URL or call `find_item()` with a transaction-scoped test session.
|
||||||
|
|
||||||
|
When several repository operations must share one transaction, pass the same session through each call. Put the transaction at the use-case boundary:
|
||||||
|
|
||||||
|
```python
|
||||||
|
async with session_factory() as session:
|
||||||
|
async with session.begin():
|
||||||
|
item = await repository.find(item_id, session=session)
|
||||||
|
await update_item(session, item, changes)
|
||||||
|
```
|
||||||
|
|
||||||
|
This preserves atomicity without making repository objects hold mutable `AsyncSession` instances across calls.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Canonical FastAPI Dependency Pattern
|
||||||
|
|
||||||
|
```python
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
|
||||||
|
from fastapi import Depends
|
||||||
|
from fastapi import Request
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||||
|
|
||||||
|
|
||||||
|
type SessionFactory = async_sessionmaker[AsyncSession]
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_session_factory(request: Request) -> SessionFactory:
|
||||||
|
return get_session_factory(request.app.state.settings.database_url)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_db_session(
|
||||||
|
session_factory: SessionFactory = Depends(resolve_session_factory),
|
||||||
|
) -> AsyncIterator[AsyncSession]:
|
||||||
|
async with session_factory() as session:
|
||||||
|
yield session
|
||||||
|
```
|
||||||
|
|
||||||
|
Route usage:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from .session import get_db_session
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/items")
|
||||||
|
async def create_item(session: AsyncSession = Depends(get_db_session)) -> dict:
|
||||||
|
async with session.begin():
|
||||||
|
# write operations here
|
||||||
|
...
|
||||||
|
return {"status": "ok"}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuration Guidance
|
||||||
|
|
||||||
|
- `expire_on_commit=False` is commonly preferred in asyncio applications to reduce accidental post-commit reload behavior.
|
||||||
|
- `AsyncSession.refresh()` is preferred over broad expiration patterns when state refresh is needed.
|
||||||
|
- [`async_sessionmaker.begin()`](https://docs.sqlalchemy.org/en/21/orm/extensions/asyncio.html#sqlalchemy.ext.asyncio.async_sessionmaker.begin) is a concise option when one scope must create a session, begin a transaction, commit on success, roll back on failure, and close. Do not use it when borrowing a caller's session.
|
||||||
|
|
||||||
|
## SQLModel Alignment
|
||||||
|
|
||||||
|
- Use SQLModel as the default model and statement layer while keeping the same session ownership model: one `async_sessionmaker`, one `AsyncSession` per request/unit-of-work.
|
||||||
|
- SQLModel does not replace SQLAlchemy async lifecycle primitives; it provides model declaration, validation, and typing ergonomics on top of them.
|
||||||
|
- Do not mix ad hoc session construction with the canonical async dependency.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Concurrency Rules
|
||||||
|
|
||||||
|
- One session per concurrent task.
|
||||||
|
- If work fans out into parallel tasks, each task receives its own AsyncSession.
|
||||||
|
- Pass sessions explicitly to service functions; avoid mutable global session state.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anti-Patterns
|
||||||
|
|
||||||
|
- A singleton/global AsyncSession reused across requests.
|
||||||
|
- Sharing one AsyncSession across parallel tasks.
|
||||||
|
- Passing an application-global AsyncSession to a repository constructor.
|
||||||
|
- Caching an `AsyncSession` instead of caching `async_sessionmaker`.
|
||||||
|
- Leaving a cached maker pointing at a disposed or replaced engine.
|
||||||
|
- Calling the session factory inside low-level access functions such as `find_item()`.
|
||||||
|
- Hidden session creation in lower access functions with no caller control.
|
||||||
|
- Closing or committing a session supplied by the caller.
|
||||||
|
- Starting a new transaction inside a helper that may receive a session already in a transaction.
|
||||||
|
- Silently starting or committing a transaction on a supplied session.
|
||||||
|
- Mixing commit/rollback ownership across layers without a declared boundary.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Operational Checks
|
||||||
|
|
||||||
|
- Exactly one cached `async_sessionmaker` exists per application engine.
|
||||||
|
- Session factory caches are cleared before their engines are disposed or replaced.
|
||||||
|
- Request handlers receive sessions from one canonical dependency.
|
||||||
|
- No code path creates AsyncSession in module import side effects.
|
||||||
|
- Background jobs and API handlers each create task-local sessions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing Checks
|
||||||
|
|
||||||
|
- Repository constructors accept a test database URL without FastAPI startup.
|
||||||
|
- Session-taking access functions accept a transaction-scoped test session directly.
|
||||||
|
- Optional-session tests verify that borrowed sessions remain open and created sessions close.
|
||||||
|
- Optional-session tests verify that neither path commits implicitly.
|
||||||
|
- Optional-transaction tests verify supplied sessions require an active transaction and remain caller-owned.
|
||||||
|
- Optional-transaction tests verify owned transactions commit on success, roll back on failure, and close their sessions.
|
||||||
|
- Cache tests clear `get_session_factory` before and after replacing engines.
|
||||||
|
- Dependency override exists for the FastAPI session factory.
|
||||||
|
- Rollback behavior is verified for failed write units.
|
||||||
|
- Parallel-task tests verify no shared AsyncSession instances.
|
||||||
|
- Lifespan tests confirm session factory is initialized and teardown-safe.
|
||||||
|
|
||||||
+8
-5
@@ -12,7 +12,7 @@
|
|||||||
- Status: adopted
|
- Status: adopted
|
||||||
- Decision level: mandatory
|
- Decision level: mandatory
|
||||||
- Applies to: api-runtime, workers, tests
|
- Applies to: api-runtime, workers, tests
|
||||||
- Last reviewed: 2026-08-06
|
- Last reviewed: 2026-07-26
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ SQLModel is designed for FastAPI, built on Pydantic and SQLAlchemy, and intended
|
|||||||
## Rules
|
## Rules
|
||||||
|
|
||||||
- Default to SQLModel for new table models and API data models.
|
- Default to SQLModel for new table models and API data models.
|
||||||
- Keep SQLAlchemy engine and factory primitives as the runtime base: `create_async_engine` and `async_sessionmaker`. For SQLModel applications, use SQLModel's `AsyncSession` wrapper so its typed `exec()` API remains available.
|
- Keep SQLAlchemy async primitives as the runtime base: `create_async_engine`, `async_sessionmaker`, and `AsyncSession`.
|
||||||
- Keep transaction and session ownership policies identical whether models are SQLAlchemy Declarative or SQLModel.
|
- Keep transaction and session ownership policies identical whether models are SQLAlchemy Declarative or SQLModel.
|
||||||
- Use SQLModel inheritance to share validated fields while keeping table, create, update, and public contracts distinct where their semantics differ.
|
- Use SQLModel inheritance to share validated fields while keeping table, create, update, and public contracts distinct where their semantics differ.
|
||||||
- Use SQLAlchemy declarative models only for a concrete unsupported mapping or third-party constraint; document the reason.
|
- Use SQLAlchemy declarative models only for a concrete unsupported mapping or third-party constraint; document the reason.
|
||||||
@@ -72,14 +72,17 @@ class UserRead(UserBase):
|
|||||||
### Pattern B: Keep SQLModel models with the async runtime
|
### Pattern B: Keep SQLModel models with the async runtime
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
from sqlmodel import select
|
from sqlmodel import select
|
||||||
|
|
||||||
async with database_scope(settings.database_url) as session_factory:
|
engine = create_async_engine(settings.database_url, pool_pre_ping=True)
|
||||||
|
session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
|
||||||
async with session_factory() as session:
|
async with session_factory() as session:
|
||||||
users = (await session.exec(select(User))).all()
|
users = (await session.scalars(select(User))).all()
|
||||||
```
|
```
|
||||||
|
|
||||||
`database_scope()` enters the cached engine lifecycle, initializes registered SQLModel metadata by default, and yields the application session factory while SQLModel supplies the model and statement layer. `sqlmodel.select()` keeps SQLModel's typing-oriented statement construction, and SQLModel's `AsyncSession` adds typed `exec()` results while retaining SQLAlchemy's async lifecycle and transaction behavior. Import `AsyncSession` from `sqlmodel.ext.asyncio.session` when working with SQLModel models; use SQLAlchemy's `AsyncSession` only when the code intentionally has no SQLModel dependency.
|
`sqlmodel.select()` keeps SQLModel's typing-oriented statement construction, while `AsyncSession.scalars()` and the surrounding lifecycle come from SQLAlchemy.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
+28
-9
@@ -1,6 +1,23 @@
|
|||||||
---
|
---
|
||||||
name: copilot-customization
|
name: copilot-customization
|
||||||
description: 'Plan, create, review, and debug GitHub Copilot and VS Code agent customizations, including instructions, prompt files, skills, custom agents, hooks, MCP servers, and repo-specific personal-mcp skill integration.'
|
description: 'Plan, create, review, and debug GitHub Copilot and VS Code agent customizations, including instructions, prompt files, skills, custom agents, hooks, MCP servers, and repo-specific personal-mcp skill integration.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: copilot-customization
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- copilot
|
||||||
|
- vscode
|
||||||
|
- customization
|
||||||
|
- instructions
|
||||||
|
- prompts
|
||||||
|
- agent-skills
|
||||||
|
- custom-agents
|
||||||
|
- hooks
|
||||||
|
- mcp
|
||||||
|
- personal-mcp
|
||||||
|
- skills
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/copilot-customization/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# Copilot Customization
|
# Copilot Customization
|
||||||
@@ -61,29 +78,31 @@ Use either:
|
|||||||
Choose one of these patterns:
|
Choose one of these patterns:
|
||||||
|
|
||||||
1. Direct URI strategy:
|
1. Direct URI strategy:
|
||||||
- Read `skill://<skill-name>/SKILL.md` when the required skill is known.
|
- Reference known resources directly, such as:
|
||||||
- Read `skill://<skill-name>/_manifest` only when supporting material may be useful.
|
- `resource://catalog/skills_index`
|
||||||
- Read selected supporting files at `skill://<skill-name>/<supporting-path>`.
|
- `resource://catalog/skills/{skill_id}`
|
||||||
|
- `resource://skills/<skill-id>/document`
|
||||||
|
- `resource://skills/<skill-id>/references/<ref-id>`
|
||||||
2. Discovery-first strategy:
|
2. Discovery-first strategy:
|
||||||
- List resources, compare native main-resource names and descriptions, then load the best matching `SKILL.md`.
|
- Start at catalog discovery (`resource://catalog/skills_index`), select the best skill match, then load the skill document and only the minimal references needed.
|
||||||
|
|
||||||
### Authoring guidance for shims
|
### Authoring guidance for shims
|
||||||
|
|
||||||
1. Keep shim content short and procedural; avoid copying large guidance blocks from Personal MCP.
|
1. Keep shim content short and procedural; avoid copying large guidance blocks from Personal MCP.
|
||||||
2. State trigger conditions clearly (for example: "when creating a new skill" or "when editing docs contracts").
|
2. State trigger conditions clearly (for example: "when creating a new skill" or "when editing docs contracts").
|
||||||
3. Specify whether to use a direct native URI or resource listing for that repo's common workflows.
|
3. Specify whether to use direct URIs or discovery for that repo's common workflows.
|
||||||
4. Prefer loading only the most relevant main file first; inspect its manifest only when needed.
|
4. Prefer loading only the most relevant skill document first; expand to references only when needed.
|
||||||
5. For stable repeated workflows, use explicit URIs. For broader or ambiguous requests, use discovery-first.
|
5. For stable repeated workflows, use explicit URIs. For broader or ambiguous requests, use discovery-first.
|
||||||
|
|
||||||
### Minimal shim examples
|
### Minimal shim examples
|
||||||
|
|
||||||
Instruction-style shim intent:
|
Instruction-style shim intent:
|
||||||
|
|
||||||
1. "For markdown edits (`applyTo: '**/*.md'`), load `skill://zensical-docs/SKILL.md` and apply Zensical-native documentation conventions unless they conflict with expected MkDocs compatibility."
|
1. "For markdown edits (`applyTo: '**/*.md'`), load `resource://skills/zensical-docs/document` and apply Zensical-native documentation conventions unless they conflict with expected MkDocs compatibility."
|
||||||
|
|
||||||
Prompt-style shim intent:
|
Prompt-style shim intent:
|
||||||
|
|
||||||
1. "For docs authoring tasks, consult `skill://zensical-docs/SKILL.md`, summarize the relevant authoring constraints, then propose the smallest markdown change for this repository."
|
1. "For docs authoring tasks, consult `resource://skills/zensical-docs/document`, summarize the relevant authoring constraints, then propose the smallest markdown change for this repository."
|
||||||
|
|
||||||
### Validation for shim implementation
|
### Validation for shim implementation
|
||||||
|
|
||||||
@@ -111,7 +130,7 @@ Before finishing:
|
|||||||
3. Confirm names match directory names where VS Code requires it.
|
3. Confirm names match directory names where VS Code requires it.
|
||||||
4. Confirm descriptions include the phrases users are likely to ask for.
|
4. Confirm descriptions include the phrases users are likely to ask for.
|
||||||
5. Confirm extra skill resources are linked from `SKILL.md`.
|
5. Confirm extra skill resources are linked from `SKILL.md`.
|
||||||
6. Confirm native discovery exposes `skill://<skill-name>/SKILL.md`, `_manifest`, and supporting-file reads.
|
6. Confirm repo skill metadata exposes the correct `resource://skills/<skill-id>/document` capability.
|
||||||
7. State any remaining ambiguity or user choice, such as personal vs workspace scope.
|
7. State any remaining ambiguity or user choice, such as personal vs workspace scope.
|
||||||
|
|
||||||
## Output Contract
|
## Output Contract
|
||||||
+11
@@ -1,6 +1,17 @@
|
|||||||
---
|
---
|
||||||
name: fastapi-uv-docker
|
name: fastapi-uv-docker
|
||||||
description: 'Audit and migrate an existing Python project to best practices for a cloud-native ASGI FastAPI app managed with uv and run with uvicorn in Docker. Use when: conforming a project to production standards, setting up src layout, configuring pyproject.toml, writing multi-stage Dockerfiles, wiring lifespan and settings, adding health endpoints, enforcing non-root container user, migrating from requirements.txt to uv.'
|
description: 'Audit and migrate an existing Python project to best practices for a cloud-native ASGI FastAPI app managed with uv and run with uvicorn in Docker. Use when: conforming a project to production standards, setting up src layout, configuring pyproject.toml, writing multi-stage Dockerfiles, wiring lifespan and settings, adding health endpoints, enforcing non-root container user, migrating from requirements.txt to uv.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: fastapi-uv-docker
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- fastapi
|
||||||
|
- uv
|
||||||
|
- uvicorn
|
||||||
|
- docker
|
||||||
|
- architecture
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/fastapi-uv-docker/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# FastAPI Project Best Practices
|
# FastAPI Project Best Practices
|
||||||
@@ -1,6 +1,17 @@
|
|||||||
---
|
---
|
||||||
name: mcp-details
|
name: mcp-details
|
||||||
description: "Reference hub for MCP and FastMCP source documentation links. Use when you need authoritative protocol, SDK, transport, and deployment docs without loading broad implementation guidance."
|
description: "Reference hub for MCP and FastMCP source documentation links. Use when you need authoritative protocol, SDK, transport, and deployment docs without loading broad implementation guidance."
|
||||||
|
x-personal-mcp:
|
||||||
|
id: mcp-details
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- mcp
|
||||||
|
- model-context-protocol
|
||||||
|
- fastmcp
|
||||||
|
- references
|
||||||
|
- source-docs
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/mcp-details/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# MCP Details
|
# MCP Details
|
||||||
-2
@@ -7,8 +7,6 @@ Use this page for MCP client setup, operational tools, and integration reference
|
|||||||
!!! info "VS Code MCP docs"
|
!!! info "VS Code MCP docs"
|
||||||
- [VS Code MCP servers overview](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
- [VS Code MCP servers overview](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
||||||
- [VS Code MCP configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration)
|
- [VS Code MCP configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration)
|
||||||
- [VS Code MCP developer guide](https://code.visualstudio.com/docs/agents/guides/mcp-developer-guide)
|
|
||||||
- [VS Code MCP Apps support](https://code.visualstudio.com/blogs/2026/01/26/mcp-apps-support)
|
|
||||||
- [VS Code Copilot customization overview](https://code.visualstudio.com/docs/copilot/customization/overview)
|
- [VS Code Copilot customization overview](https://code.visualstudio.com/docs/copilot/customization/overview)
|
||||||
|
|
||||||
## Debugging and Inspection
|
## Debugging and Inspection
|
||||||
+2
-13
@@ -13,19 +13,8 @@ Use this page for implementation-oriented links across MCP SDKs and FastMCP.
|
|||||||
|
|
||||||
!!! info "FastMCP sources"
|
!!! info "FastMCP sources"
|
||||||
- [FastMCP project documentation](https://gofastmcp.com/)
|
- [FastMCP project documentation](https://gofastmcp.com/)
|
||||||
- [FastMCP server identity and behavior](https://gofastmcp.com/servers/server)
|
- [FastMCP GitHub repository](https://github.com/jlowin/fastmcp)
|
||||||
- [FastMCP providers overview](https://gofastmcp.com/servers/providers/overview)
|
- [FastMCP examples directory](https://github.com/jlowin/fastmcp/tree/main/examples)
|
||||||
- [FastMCP custom providers](https://gofastmcp.com/servers/providers/custom)
|
|
||||||
- [FastMCP skills provider](https://gofastmcp.com/servers/providers/skills)
|
|
||||||
- [FastMCP tools and annotations](https://gofastmcp.com/servers/tools)
|
|
||||||
- [FastMCP resources and templates](https://gofastmcp.com/servers/resources)
|
|
||||||
- [FastMCP prompts](https://gofastmcp.com/servers/prompts)
|
|
||||||
- [FastMCP filesystem provider](https://gofastmcp.com/servers/providers/filesystem)
|
|
||||||
- [FastMCP argument completion](https://gofastmcp.com/servers/completions)
|
|
||||||
- [FastMCP component icons](https://gofastmcp.com/servers/icons)
|
|
||||||
- [FastMCP Apps](https://gofastmcp.com/apps/overview)
|
|
||||||
- [FastMCP GitHub repository](https://github.com/PrefectHQ/fastmcp)
|
|
||||||
- [FastMCP examples directory](https://github.com/PrefectHQ/fastmcp/tree/main/examples)
|
|
||||||
- [FastMCP PyPI package](https://pypi.org/project/fastmcp/)
|
- [FastMCP PyPI package](https://pypi.org/project/fastmcp/)
|
||||||
|
|
||||||
## Server Implementation Patterns
|
## Server Implementation Patterns
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
---
|
||||||
|
name: nicegui-ui-customization
|
||||||
|
description: 'Design and implement production NiceGUI UIs with reusable components, Tailwind-first styling, event-driven interactions, and troubleshooting for uploads, state, and static assets. Use when building or refactoring NiceGUI pages and interaction flows.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: nicegui-ui-customization
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- nicegui
|
||||||
|
- fastapi
|
||||||
|
- ui
|
||||||
|
- customization
|
||||||
|
- frontend
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/nicegui-ui-customization/document
|
||||||
|
---
|
||||||
|
|
||||||
|
# NiceGUI UI Customization Workflow
|
||||||
|
|
||||||
|
Create, style, and ship production NiceGUI UI flows with a repeatable process. The workflow keeps structure in Python, favors Tailwind and Quasar APIs for styling, and uses event-driven interaction patterns over ad-hoc polling.
|
||||||
|
|
||||||
|
## When To Use
|
||||||
|
|
||||||
|
- Building a new NiceGUI page or dashboard
|
||||||
|
- Refactoring a page into reusable components
|
||||||
|
- Adding file upload, form submission, live status, or background-job UX
|
||||||
|
- Troubleshooting race conditions, stale assets, or inconsistent state updates
|
||||||
|
|
||||||
|
## Target Outcome
|
||||||
|
|
||||||
|
Deliver a responsive, accessible UI flow that:
|
||||||
|
|
||||||
|
- keeps clear boundaries between page adapters, reusable components, and services
|
||||||
|
- uses Tailwind-first styling with minimal custom CSS
|
||||||
|
- updates UI through events and bindings
|
||||||
|
- has validation, user feedback, and failure handling
|
||||||
|
- passes a production-readiness check at the end
|
||||||
|
|
||||||
|
## Progressive Loading References
|
||||||
|
|
||||||
|
Load these references only when needed:
|
||||||
|
|
||||||
|
- Architecture and styling rules: [architecture and styling](./references/architecture-and-styling.md)
|
||||||
|
- Event and state interaction patterns: [interaction patterns](./references/interaction-patterns.md)
|
||||||
|
- Troubleshooting and release gates: [troubleshooting and quality gates](./references/troubleshooting-and-quality-gates.md)
|
||||||
|
|
||||||
|
## Procedure
|
||||||
|
|
||||||
|
### 1. Define the UI Slice
|
||||||
|
|
||||||
|
- Capture the user-visible outcome for this task in one sentence.
|
||||||
|
- Identify route-level page modules to touch.
|
||||||
|
- Identify service operations needed by the UI.
|
||||||
|
|
||||||
|
Completion check:
|
||||||
|
|
||||||
|
- You can name the target page, component candidates, and service calls before coding.
|
||||||
|
|
||||||
|
### 2. Choose Component Extraction Strategy
|
||||||
|
|
||||||
|
Decision point:
|
||||||
|
|
||||||
|
- If a layout pattern appears in 2 or more pages, extract it to `ui/components/`.
|
||||||
|
- If a pattern is page-specific, keep it in the page module.
|
||||||
|
|
||||||
|
Completion check:
|
||||||
|
|
||||||
|
- Reused UI patterns are encapsulated as callable components.
|
||||||
|
|
||||||
|
### 3. Build Responsive Layout First
|
||||||
|
|
||||||
|
- Use Tailwind utility classes for structure and spacing.
|
||||||
|
- Use responsive breakpoints (`sm:`, `md:`, `lg:`).
|
||||||
|
- Reserve `.style()` for dynamic values that cannot be expressed with classes.
|
||||||
|
|
||||||
|
Completion check:
|
||||||
|
|
||||||
|
- Layout works at mobile and desktop widths without custom CSS overrides.
|
||||||
|
|
||||||
|
### 4. Add Reactive State And Events
|
||||||
|
|
||||||
|
- Use bindable dataclasses for local page state.
|
||||||
|
- Prefer event handlers (`on_click`, `on_upload`, etc.) over periodic polling.
|
||||||
|
- Trigger explicit refreshes with `@ui.refreshable` where needed.
|
||||||
|
|
||||||
|
Decision point by interaction type:
|
||||||
|
|
||||||
|
- File upload: validate size/type, delegate storage to a service, notify success/failure.
|
||||||
|
- Form submit: bind inputs to dataclass fields, validate in service layer, clear state on success.
|
||||||
|
- Real-time status: use SSE or WebSocket for push updates.
|
||||||
|
- Long jobs: run in background task, update status endpoint or stream.
|
||||||
|
|
||||||
|
Completion check:
|
||||||
|
|
||||||
|
- Every user action has explicit positive and negative feedback via `ui.notify()`.
|
||||||
|
|
||||||
|
### 5. Apply Styling Strategy
|
||||||
|
|
||||||
|
Preferred order:
|
||||||
|
|
||||||
|
1. Tailwind utility classes
|
||||||
|
2. Quasar props
|
||||||
|
3. Reusable styled component functions
|
||||||
|
|
||||||
|
Only if absolutely necessary:
|
||||||
|
|
||||||
|
- Load minimal custom CSS once at startup in `bootstrap.py`.
|
||||||
|
- Keep custom CSS tokenized (variables) and documented.
|
||||||
|
|
||||||
|
Completion check:
|
||||||
|
|
||||||
|
- Styling is mostly class/props-driven and not dependent on scattered ad-hoc CSS.
|
||||||
|
|
||||||
|
### 6. Harden Against Common Failures
|
||||||
|
|
||||||
|
- Prevent duplicate submissions by disabling controls during in-flight operations.
|
||||||
|
- Avoid overlapping timers for the same state target.
|
||||||
|
- Serialize dependent updates (`await` service call before mutation/render).
|
||||||
|
- Verify static mount paths and cache behavior for changed assets.
|
||||||
|
|
||||||
|
Completion check:
|
||||||
|
|
||||||
|
- Race conditions and stale asset symptoms are addressed with explicit safeguards.
|
||||||
|
|
||||||
|
### 7. Final Production Readiness Review
|
||||||
|
|
||||||
|
Pass all checks:
|
||||||
|
|
||||||
|
- Structure: pages, components, services follow one-way dependency flow.
|
||||||
|
- Responsiveness: tested at small and large viewport widths.
|
||||||
|
- Accessibility: labels, button text, and action visibility are clear.
|
||||||
|
- Reliability: validation and exception paths produce user-facing notifications.
|
||||||
|
- Maintainability: repeated UI patterns are extracted; business logic stays in services.
|
||||||
|
|
||||||
|
If any check fails, return to the relevant step and iterate.
|
||||||
|
|
||||||
|
## Completion Contract
|
||||||
|
|
||||||
|
This workflow is complete when:
|
||||||
|
|
||||||
|
- the page flow meets the target outcome
|
||||||
|
- architecture boundaries are preserved
|
||||||
|
- chosen interaction pattern is implemented with explicit success and failure feedback
|
||||||
|
- troubleshooting checks pass
|
||||||
|
- production-readiness gate passes
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Architecture and Styling Reference
|
||||||
|
|
||||||
|
## Project Boundaries
|
||||||
|
|
||||||
|
Use this dependency direction:
|
||||||
|
|
||||||
|
- pages import components and services
|
||||||
|
- components contain presentation logic only
|
||||||
|
- services contain business logic and do not import UI
|
||||||
|
- static assets are mounted and loaded once at bootstrap
|
||||||
|
|
||||||
|
Suggested module split:
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/app/
|
||||||
|
ui/pages/
|
||||||
|
ui/components/
|
||||||
|
ui/static/
|
||||||
|
services/
|
||||||
|
api/
|
||||||
|
bootstrap.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Component Extraction Rules
|
||||||
|
|
||||||
|
Extract to ui/components when a pattern appears in two or more pages.
|
||||||
|
|
||||||
|
Keep in-page if the layout is specific to a single route.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def card_section(title: str, content: str) -> ui.card:
|
||||||
|
with ui.card().classes("w-full max-w-md") as card:
|
||||||
|
ui.label(title).classes("text-lg font-bold")
|
||||||
|
ui.label(content).classes("text-gray-600")
|
||||||
|
return card
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tailwind-First Layout Pattern
|
||||||
|
|
||||||
|
Use Tailwind utility classes for structure and spacing.
|
||||||
|
Use breakpoint classes for responsive behavior.
|
||||||
|
Use .style() only for values that must be computed dynamically.
|
||||||
|
|
||||||
|
```python
|
||||||
|
with ui.column().classes("w-full"):
|
||||||
|
with ui.row().classes("w-full gap-4 flex-wrap sm:flex-nowrap"):
|
||||||
|
ui.card().classes("flex-1 min-w-64")
|
||||||
|
ui.card().classes("flex-1 min-w-64")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Styling Decision Order
|
||||||
|
|
||||||
|
1. Tailwind utility classes
|
||||||
|
2. Quasar props
|
||||||
|
3. Reusable styled component functions
|
||||||
|
4. Minimal custom CSS loaded once at bootstrap (only when needed)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
|
app.mount("/static", StaticFiles(directory="src/app/static"), name="static")
|
||||||
|
ui.add_css(open("src/app/static/css/base.css").read())
|
||||||
|
```
|
||||||
|
|
||||||
|
## Static Asset Rules
|
||||||
|
|
||||||
|
- Keep custom CSS small and tokenized with variables.
|
||||||
|
- Avoid per-page CSS injection.
|
||||||
|
- Verify static mount paths and reverse proxy rewrites.
|
||||||
|
|
||||||
|
## Links
|
||||||
|
|
||||||
|
!!! info "Primary sources"
|
||||||
|
- [NiceGUI elements](https://nicegui.io/documentation/element)
|
||||||
|
- [NiceGUI binding properties](https://nicegui.io/documentation/section_binding_properties)
|
||||||
|
- [Tailwind utility-first styling](https://tailwindcss.com/docs/utility-first)
|
||||||
|
- [Quasar components](https://quasar.dev/vue-components)
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# Interaction Patterns Reference
|
||||||
|
|
||||||
|
## Reactive State
|
||||||
|
|
||||||
|
Use bindable dataclasses for local page state.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from dataclasses import field
|
||||||
|
from nicegui import binding, ui
|
||||||
|
|
||||||
|
@binding.bindable_dataclass
|
||||||
|
class PageState:
|
||||||
|
selected_id: int | None = None
|
||||||
|
items: list = field(default_factory=list)
|
||||||
|
|
||||||
|
state = PageState()
|
||||||
|
ui.label().bind_text_from(state, "selected_id")
|
||||||
|
```
|
||||||
|
|
||||||
|
## File Upload Pattern
|
||||||
|
|
||||||
|
- Validate extension and size before storing.
|
||||||
|
- Delegate storage to a service method.
|
||||||
|
- Notify success and failure explicitly.
|
||||||
|
|
||||||
|
```python
|
||||||
|
async def handle_upload(e: ui.events.UploadEventArguments):
|
||||||
|
try:
|
||||||
|
if e.size > 10 * 1024 * 1024:
|
||||||
|
raise ValueError("File too large")
|
||||||
|
if not e.name.endswith(".pdf"):
|
||||||
|
raise ValueError("Only PDF allowed")
|
||||||
|
await file_service.store(e.content.read(), e.name)
|
||||||
|
ui.notify(f"Uploaded: {e.name}", type="positive")
|
||||||
|
except ValueError as err:
|
||||||
|
ui.notify(str(err), type="negative")
|
||||||
|
|
||||||
|
ui.upload(on_upload=handle_upload, auto_upload=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Form Submission Pattern
|
||||||
|
|
||||||
|
- Bind UI inputs to dataclass fields.
|
||||||
|
- Perform validation in the service layer.
|
||||||
|
- Clear form state on success.
|
||||||
|
|
||||||
|
```python
|
||||||
|
@binding.bindable_dataclass
|
||||||
|
class FormData:
|
||||||
|
name: str = ""
|
||||||
|
email: str = ""
|
||||||
|
|
||||||
|
data = FormData()
|
||||||
|
ui.input("Name").bind_value(data, "name")
|
||||||
|
ui.input("Email").bind_value(data, "email")
|
||||||
|
|
||||||
|
async def on_submit():
|
||||||
|
try:
|
||||||
|
await user_service.create_user(name=data.name, email=data.email)
|
||||||
|
ui.notify("User created", type="positive")
|
||||||
|
data.name = data.email = ""
|
||||||
|
except ValueError as err:
|
||||||
|
ui.notify(str(err), type="negative")
|
||||||
|
|
||||||
|
ui.button("Submit").on_click(on_submit)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Real-Time Updates Decision
|
||||||
|
|
||||||
|
Use SSE for one-way status streaming.
|
||||||
|
Use WebSocket for bidirectional messaging.
|
||||||
|
|
||||||
|
SSE endpoint example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
@app.get("/events/status")
|
||||||
|
async def status_stream():
|
||||||
|
async def gen():
|
||||||
|
while True:
|
||||||
|
yield f"data: {await get_status()}\\n\\n"
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
return StreamingResponse(gen(), media_type="text/event-stream")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Background Work Pattern
|
||||||
|
|
||||||
|
- Start long jobs in FastAPI background tasks.
|
||||||
|
- Expose status via endpoint or streaming channel.
|
||||||
|
- Guard buttons against duplicate submissions during in-flight tasks.
|
||||||
|
|
||||||
|
## Explicit Refresh Pattern
|
||||||
|
|
||||||
|
Use @ui.refreshable and call refresh intentionally instead of polling unrelated state.
|
||||||
|
|
||||||
|
```python
|
||||||
|
@ui.refreshable
|
||||||
|
async def item_list():
|
||||||
|
items = await service.list()
|
||||||
|
for item in items:
|
||||||
|
ui.label(item.name)
|
||||||
|
|
||||||
|
ui.button("Refresh").on_click(lambda: item_list.refresh())
|
||||||
|
```
|
||||||
|
|
||||||
|
## Links
|
||||||
|
|
||||||
|
!!! info "Primary sources"
|
||||||
|
- [NiceGUI action events](https://nicegui.io/documentation/section_action_events)
|
||||||
|
- [FastAPI server-sent events](https://fastapi.tiangolo.com/advanced/server-sent-events/)
|
||||||
|
- [FastAPI WebSockets](https://fastapi.tiangolo.com/advanced/websockets/)
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Troubleshooting and Quality Gates
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Upload Errors
|
||||||
|
|
||||||
|
- Validate extension and size before storage.
|
||||||
|
- Catch expected exceptions and return negative notifications.
|
||||||
|
- Log unexpected exceptions with request context.
|
||||||
|
|
||||||
|
### UI Race Conditions
|
||||||
|
|
||||||
|
- Disable triggering controls during async work.
|
||||||
|
- Remove duplicate timers and listeners targeting the same state.
|
||||||
|
- Ensure service call ordering is deterministic before render updates.
|
||||||
|
|
||||||
|
### Asset Caching
|
||||||
|
|
||||||
|
- Confirm static mount and proxy rewrite correctness.
|
||||||
|
- Add cache-busting query strings for changed assets.
|
||||||
|
- Avoid per-page CSS injection.
|
||||||
|
|
||||||
|
### Navigation and State Drift
|
||||||
|
|
||||||
|
- Avoid global mutable UI state.
|
||||||
|
- Keep state request-scoped or service-managed.
|
||||||
|
- Rehydrate page data during route load.
|
||||||
|
|
||||||
|
## Production Readiness Gate
|
||||||
|
|
||||||
|
Pass all checks before shipping:
|
||||||
|
|
||||||
|
- Structure: one-way dependencies between pages, components, and services.
|
||||||
|
- Responsiveness: UI validated at both small and large viewport widths.
|
||||||
|
- Accessibility: labels and actions are clear and readable.
|
||||||
|
- Reliability: validation and exception paths surface user feedback.
|
||||||
|
- Maintainability: repeated UI patterns are extracted; business logic remains in services.
|
||||||
|
|
||||||
|
If any check fails, return to the workflow step that owns that concern.
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
---
|
||||||
|
name: nicegui
|
||||||
|
description: 'Design and scaffold a production-ready NiceGUI + FastAPI application architecture. Use for multi-page app planning, package boundaries, optional DB/LangGraph/docs integration, and implementation checklists.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: nicegui
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- nicegui
|
||||||
|
- fastapi
|
||||||
|
- ui
|
||||||
|
- architecture
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/nicegui/document
|
||||||
|
---
|
||||||
|
|
||||||
|
# NiceGUI
|
||||||
|
|
||||||
|
Design a production-minded NiceGUI + FastAPI architecture with clear boundaries, optional extensions, and a concrete implementation checklist.
|
||||||
|
|
||||||
|
## When to Use
|
||||||
|
|
||||||
|
- You need a reusable architecture plan before implementing a NiceGUI app.
|
||||||
|
- You want FastAPI app-factory structure and lifespan wiring.
|
||||||
|
- You need optional guidance for database, LangGraph workflows, or mounted static docs.
|
||||||
|
- You want output that is concise, structured, and implementation-ready.
|
||||||
|
|
||||||
|
## Inputs to Collect
|
||||||
|
|
||||||
|
Collect these inputs up front. If not provided, make safe defaults and state assumptions.
|
||||||
|
|
||||||
|
- Product scope and primary user journeys.
|
||||||
|
- Required pages and route map.
|
||||||
|
- Whether persistent data is required.
|
||||||
|
- Whether AI orchestration (multi-step, streaming, approvals) is required.
|
||||||
|
- Whether generated docs should be mounted in-app.
|
||||||
|
- Runtime/deployment constraints (single service vs split services, environment requirements).
|
||||||
|
|
||||||
|
## Outcome
|
||||||
|
|
||||||
|
Produce:
|
||||||
|
|
||||||
|
- A concise architecture explanation.
|
||||||
|
- How core services, UI pages, and UI components fit together.
|
||||||
|
- Explicit decision on DB ownership or involvement.
|
||||||
|
- Explicit decision on AI workflow (or no AI).
|
||||||
|
- A checklist implementation plan organized by package and domain.
|
||||||
|
|
||||||
|
## Procedure
|
||||||
|
|
||||||
|
1. Frame the baseline architecture.
|
||||||
|
2. Choose optional extensions (DB, AI, docs) using decision points below.
|
||||||
|
3. Map modules, dependencies, and key boundaries.
|
||||||
|
4. Define async behavior and UI responsiveness expectations.
|
||||||
|
5. Define key functions/classes and configuration surfaces.
|
||||||
|
6. Produce phased checklist with rollout or migration notes when relevant.
|
||||||
|
7. Run completion checks before returning.
|
||||||
|
|
||||||
|
### 1) Baseline architecture
|
||||||
|
|
||||||
|
Use a src-layout with FastAPI as the ASGI app and NiceGUI registered via composition.
|
||||||
|
|
||||||
|
- App factory pattern: `create_app()`.
|
||||||
|
- Lifespan for startup and shutdown resource management.
|
||||||
|
- `api/` for HTTP handlers, `services/` for business logic.
|
||||||
|
- `ui/pages/` for page modules, `ui/components/` for shared UI.
|
||||||
|
- Health endpoint on FastAPI side: `/healthz`.
|
||||||
|
|
||||||
|
Recommended base shape:
|
||||||
|
|
||||||
|
```text
|
||||||
|
.
|
||||||
|
├─ pyproject.toml
|
||||||
|
├─ .env.example
|
||||||
|
├─ README.md
|
||||||
|
├─ src/
|
||||||
|
│ └─ app/
|
||||||
|
│ ├─ __init__.py
|
||||||
|
│ ├─ main.py
|
||||||
|
│ ├─ bootstrap.py
|
||||||
|
│ ├─ config.py
|
||||||
|
│ ├─ logging.py
|
||||||
|
│ ├─ api/
|
||||||
|
│ │ ├─ __init__.py
|
||||||
|
│ │ └─ health.py
|
||||||
|
│ ├─ services/
|
||||||
|
│ │ ├─ __init__.py
|
||||||
|
│ │ └─ example_service.py
|
||||||
|
│ └─ ui/
|
||||||
|
│ ├─ __init__.py
|
||||||
|
│ ├─ components/
|
||||||
|
│ │ ├─ __init__.py
|
||||||
|
│ │ └─ nav.py
|
||||||
|
│ └─ pages/
|
||||||
|
│ ├─ __init__.py
|
||||||
|
│ ├─ home.py
|
||||||
|
│ ├─ dashboard.py
|
||||||
|
│ └─ about.py
|
||||||
|
└─ tests/
|
||||||
|
├─ test_health.py
|
||||||
|
└─ test_pages_registration.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2) Decision points
|
||||||
|
|
||||||
|
#### Database needed?
|
||||||
|
|
||||||
|
- If no: keep `services/` pure and skip persistence layers.
|
||||||
|
- If yes: add `db/` package with engine/session/model/repository layering.
|
||||||
|
- Prefer one process-level engine and request-scoped sessions via `yield`.
|
||||||
|
- Prefer Alembic migrations for schema changes.
|
||||||
|
|
||||||
|
#### AI workflow needed?
|
||||||
|
|
||||||
|
- If no: keep `services/` focused on app logic only.
|
||||||
|
- If yes: add `ai/` package (state, nodes, graph, runtime, contracts).
|
||||||
|
- Keep graph internals out of `ui/pages/` and API handlers.
|
||||||
|
- Use stable thread/session IDs for resumable flows.
|
||||||
|
|
||||||
|
#### Mounted docs needed?
|
||||||
|
|
||||||
|
- If no: skip docs mounting.
|
||||||
|
- If yes: mount generated static site under configurable route (default `/docs`).
|
||||||
|
- Keep docs mounting in composition layer, not page modules.
|
||||||
|
|
||||||
|
### 3) Page and component registration
|
||||||
|
|
||||||
|
- Require at minimum page modules for `/`, `/dashboard`, `/about`.
|
||||||
|
- Prefer explicit registration pattern:
|
||||||
|
- `ui/pages/__init__.py` exports `register_pages()`.
|
||||||
|
- Each page module exports `register_page()`.
|
||||||
|
- Shared shell components (header/nav/drawer) live in `ui/components/`.
|
||||||
|
|
||||||
|
### 4) Dependency direction rules
|
||||||
|
|
||||||
|
Prefer:
|
||||||
|
|
||||||
|
- `main/bootstrap` -> `config/logging` + `api` + `ui/pages` + `services`
|
||||||
|
- `api` -> `services`
|
||||||
|
- `ui/pages` -> `ui/components` + `services`
|
||||||
|
- `services` -> helpers/clients (and `db/` when enabled)
|
||||||
|
|
||||||
|
Avoid reverse imports from services into API or UI modules.
|
||||||
|
|
||||||
|
### 5) Async and UI responsiveness rules
|
||||||
|
|
||||||
|
- Prefer `async def` for page handlers, service methods, and integrations when the call path includes I/O.
|
||||||
|
- Use non-blocking clients/libraries where possible so long-running I/O does not freeze UI updates.
|
||||||
|
- Do not run blocking calls (`time.sleep`, blocking HTTP/database clients) in UI event handlers.
|
||||||
|
- For heavy CPU work, offload to worker/background execution and keep the UI loop free.
|
||||||
|
- Show progress states for long actions (disable action button, show spinner/progress text, re-enable on completion).
|
||||||
|
- Stream or chunk incremental results to the UI when workflows are multi-step or long-running.
|
||||||
|
- Keep cancellation and timeout behavior explicit for user-triggered long tasks.
|
||||||
|
- Ensure exceptions from async tasks are surfaced with user-friendly feedback and logged for diagnostics.
|
||||||
|
|
||||||
|
### 6) Testing minimums
|
||||||
|
|
||||||
|
- Test FastAPI health route behavior.
|
||||||
|
- Test page registration wiring.
|
||||||
|
- If DB enabled: session lifecycle and rollback behavior tests.
|
||||||
|
- If AI enabled: graph happy path and interrupt/resume coverage.
|
||||||
|
- If docs enabled: mounted docs route returns index page.
|
||||||
|
- For async flows: test long-running actions preserve UI responsiveness (loading state, completion state, and error state).
|
||||||
|
|
||||||
|
### 7) Styling architecture
|
||||||
|
|
||||||
|
- Keep structure and layout in Python modules using NiceGUI class composition.
|
||||||
|
- Keep visual polish in shared CSS files, loaded once at startup.
|
||||||
|
- Prefer semantic reusable classes over ad hoc per-page styling.
|
||||||
|
|
||||||
|
## Completion Checks
|
||||||
|
|
||||||
|
- Uses app factory and FastAPI lifespan.
|
||||||
|
- Pages are modularized (not single-file UI).
|
||||||
|
- Health endpoint exists on FastAPI side.
|
||||||
|
- Dependency direction is clean and one-way.
|
||||||
|
- Async-first guidance is applied where I/O exists, with explicit non-blocking UX states.
|
||||||
|
- Optional DB/AI/docs decisions are explicit and reflected in structure.
|
||||||
|
- Output includes architecture summary and package-organized checklist.
|
||||||
|
|
||||||
|
## Output Contract
|
||||||
|
|
||||||
|
Return:
|
||||||
|
|
||||||
|
- Concise high-level architecture.
|
||||||
|
- How core services, pages, and shared components fit.
|
||||||
|
- DB involvement and ownership stance.
|
||||||
|
- AI workflow stance and runtime flow.
|
||||||
|
- Checklist plan by package and domain:
|
||||||
|
- key functions/classes
|
||||||
|
- settings/config surfaces
|
||||||
|
- rollout/migration notes (when relevant)
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
|
||||||
|
- Do not collapse all pages into one file.
|
||||||
|
- Do not use globals or implicit global side effects.
|
||||||
|
- Do not block UI event handlers with synchronous I/O or long CPU tasks.
|
||||||
|
- Always define loading/progress/error states for long user-triggered actions.
|
||||||
|
- Keep code minimal but production-minded.
|
||||||
|
- Prefer clarity and maintainability over clever abstractions.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Architecture and integration details: [NiceGUI architecture reference](./references/architecture.md)
|
||||||
|
- Dataclass binding deep dive: [Bindable dataclasses in NiceGUI](./references/binding-dataclasses.md)
|
||||||
|
- Source documentation links: [NiceGUI source documentation](./references/source-documentation.md)
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# NiceGUI Architecture Reference
|
||||||
|
|
||||||
|
This reference expands the workflow in the main skill file and is loaded only when needed.
|
||||||
|
|
||||||
|
## Baseline package boundaries
|
||||||
|
|
||||||
|
- `main.py`: process entrypoint only.
|
||||||
|
- `bootstrap.py`: app composition, router wiring, page registration, lifespan orchestration.
|
||||||
|
- `config.py`: typed settings and env parsing.
|
||||||
|
- `logging.py`: centralized logging setup.
|
||||||
|
- `api/`: HTTP transport layer; delegates to services.
|
||||||
|
- `services/`: business/use-case logic.
|
||||||
|
- `ui/pages/`: route-level NiceGUI pages.
|
||||||
|
- `ui/components/`: shared UI building blocks.
|
||||||
|
|
||||||
|
## Required baseline behavior
|
||||||
|
|
||||||
|
- FastAPI is the base ASGI app.
|
||||||
|
- NiceGUI pages are modular and registered from page modules.
|
||||||
|
- Minimum pages: `/`, `/dashboard`, `/about`.
|
||||||
|
- FastAPI health route: `/healthz`.
|
||||||
|
- Lifespan handles startup/shutdown resources.
|
||||||
|
- No global side effects at import time.
|
||||||
|
|
||||||
|
## Optional extension: Database
|
||||||
|
|
||||||
|
Use only if persistence is required.
|
||||||
|
|
||||||
|
Suggested additions:
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/app/db/
|
||||||
|
├─ __init__.py
|
||||||
|
├─ base.py
|
||||||
|
├─ session.py
|
||||||
|
├─ models/
|
||||||
|
└─ repositories/
|
||||||
|
```
|
||||||
|
|
||||||
|
Guidelines:
|
||||||
|
|
||||||
|
- One engine and one sessionmaker per process.
|
||||||
|
- Request-scoped session dependency using `yield`.
|
||||||
|
- Explicit transaction boundaries in service/repository flows.
|
||||||
|
- Avoid shared sessions across concurrent tasks.
|
||||||
|
- Use Alembic as schema source of truth.
|
||||||
|
|
||||||
|
## Optional extension: LangGraph AI
|
||||||
|
|
||||||
|
Use only for multi-step AI orchestration or human-in-the-loop workflows.
|
||||||
|
|
||||||
|
Suggested additions:
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/app/ai/
|
||||||
|
├─ state.py
|
||||||
|
├─ nodes/
|
||||||
|
├─ graphs/
|
||||||
|
├─ runtime.py
|
||||||
|
└─ contracts.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Guidelines:
|
||||||
|
|
||||||
|
- Keep graph internals outside API/UI modules.
|
||||||
|
- Invoke graph through `services/ai_service.py`.
|
||||||
|
- Use stable thread/session IDs for resumable sessions.
|
||||||
|
- Keep interrupt payloads JSON-serializable.
|
||||||
|
|
||||||
|
## Optional extension: Mounted static docs
|
||||||
|
|
||||||
|
Use only when generated docs should be served in-app.
|
||||||
|
|
||||||
|
Suggested settings:
|
||||||
|
|
||||||
|
- `docs_enabled`
|
||||||
|
- `docs_mount_path`
|
||||||
|
- `docs_site_dir`
|
||||||
|
- `docs_require_build` (optional)
|
||||||
|
|
||||||
|
Guidelines:
|
||||||
|
|
||||||
|
- Mount docs in composition layer (`bootstrap.py`).
|
||||||
|
- Normalize mount path and avoid route conflicts.
|
||||||
|
- Warn on missing build artifacts unless strict mode is enabled.
|
||||||
|
|
||||||
|
## Suggested output quality criteria
|
||||||
|
|
||||||
|
- Clear architecture summary with assumptions.
|
||||||
|
- Explicit decisions for DB, AI, and docs.
|
||||||
|
- Package-scoped implementation checklist.
|
||||||
|
- Minimal test plan aligned to enabled features.
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
# Binding Dataclasses Deep Dive
|
||||||
|
|
||||||
|
This reference explains how to model state with NiceGUI bindable dataclasses and how to avoid common update and performance pitfalls.
|
||||||
|
|
||||||
|
## Primary Sources
|
||||||
|
|
||||||
|
- NiceGUI binding docs: [Binding properties](https://www.nicegui.io/documentation/section_binding_properties)
|
||||||
|
- Python dataclass docs: [dataclasses module](https://docs.python.org/3/library/dataclasses.html)
|
||||||
|
- Data class design rationale: [PEP 557](https://peps.python.org/pep-0557/)
|
||||||
|
|
||||||
|
## What bindable_dataclass changes
|
||||||
|
|
||||||
|
`@binding.bindable_dataclass` extends standard dataclasses by turning fields into bindable properties so UI bindings can propagate immediately when a field is assigned.
|
||||||
|
|
||||||
|
Baseline pattern:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from nicegui import binding, ui
|
||||||
|
|
||||||
|
@binding.bindable_dataclass
|
||||||
|
class Profile:
|
||||||
|
name: str = 'Ada'
|
||||||
|
age: int = 37
|
||||||
|
|
||||||
|
profile = Profile()
|
||||||
|
|
||||||
|
ui.input('Name').bind_value(profile, 'name')
|
||||||
|
ui.number('Age', min=0).bind_value(profile, 'age')
|
||||||
|
ui.label().bind_text_from(profile, 'name', backward=lambda n: f'User: {n}')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Propagation model and performance
|
||||||
|
|
||||||
|
NiceGUI distinguishes between two link types:
|
||||||
|
|
||||||
|
- Bindable properties: efficient, event-like propagation on assignment.
|
||||||
|
- Active links: polled in a refresh loop (default every 0.1s).
|
||||||
|
|
||||||
|
Practical implications:
|
||||||
|
|
||||||
|
- Prefer bindable dataclasses for frequently updated form state.
|
||||||
|
- Keep transform functions pure and side-effect free.
|
||||||
|
- If many active links exist, tune `binding_refresh_interval` in `ui.run(...)` carefully.
|
||||||
|
|
||||||
|
## Dataclass modeling rules that matter for binding
|
||||||
|
|
||||||
|
- Use `field(default_factory=...)` for mutable defaults.
|
||||||
|
- Avoid `frozen=True` for models that should be edited from UI controls.
|
||||||
|
- Use `slots=True` only when you have confirmed compatibility with your inheritance and extension needs.
|
||||||
|
- Keep UI-editable fields explicit and typed.
|
||||||
|
|
||||||
|
Example with safe mutable defaults:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from dataclasses import field
|
||||||
|
from nicegui import binding
|
||||||
|
|
||||||
|
@binding.bindable_dataclass
|
||||||
|
class Filters:
|
||||||
|
query: str = ''
|
||||||
|
tags: list[str] = field(default_factory=list)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Nested structures and binding paths
|
||||||
|
|
||||||
|
NiceGUI supports nested key paths via tuples for nested data (for example dictionaries and nested structures).
|
||||||
|
|
||||||
|
```python
|
||||||
|
from nicegui import ui
|
||||||
|
|
||||||
|
data = {'user': {'name': 'Ada'}}
|
||||||
|
|
||||||
|
ui.input('Name').bind_value(data, ('user', 'name'))
|
||||||
|
ui.label().bind_text_from(data, ('user', 'name'))
|
||||||
|
```
|
||||||
|
|
||||||
|
When using nested dataclasses, keep updates explicit and predictable at the field level.
|
||||||
|
|
||||||
|
## Strictness and refactor safety
|
||||||
|
|
||||||
|
Binding can warn when attributes do not exist.
|
||||||
|
|
||||||
|
- Object attributes are checked by default.
|
||||||
|
- Dictionary keys are not checked by default.
|
||||||
|
- Use `strict=True` when you want missing-key warnings for dict-backed state.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from nicegui import app, ui
|
||||||
|
|
||||||
|
ui.input().bind_value(app.storage.user, 'display_name', strict=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common pitfalls and safer alternatives
|
||||||
|
|
||||||
|
- Pitfall: mutating nested mutable values in place and expecting immediate UI sync.
|
||||||
|
- Safer alternative: assign back to the bound field after updates so change propagation is explicit.
|
||||||
|
|
||||||
|
- Pitfall: heavy transform functions in bindings.
|
||||||
|
- Safer alternative: keep transformations cheap and deterministic; move heavy work to event handlers.
|
||||||
|
|
||||||
|
- Pitfall: one model shared across unrelated pages or users.
|
||||||
|
- Safer alternative: scope model instances to page/client/user context as needed.
|
||||||
|
|
||||||
|
## Version notes to remember
|
||||||
|
|
||||||
|
- `bindable_dataclass` added in NiceGUI 2.11.0.
|
||||||
|
- Binding `strict` behavior documented as added in NiceGUI 3.0.0.
|
||||||
|
- Tuple paths for nested properties documented as added in NiceGUI 3.10.0.
|
||||||
|
- Depth-first binding propagation update documented in NiceGUI 2.16.0.
|
||||||
|
|
||||||
|
Verify behavior against the NiceGUI version pinned in your project before relying on version-specific semantics.
|
||||||
|
|
||||||
|
## Quick checklist
|
||||||
|
|
||||||
|
- Choose bindable dataclasses for interactive form-like state.
|
||||||
|
- Use `default_factory` for mutable fields.
|
||||||
|
- Keep transform functions pure.
|
||||||
|
- Use strict mode intentionally.
|
||||||
|
- Re-check version notes before migration work.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Source Documentation
|
||||||
|
|
||||||
|
Use these links for framework-specific details.
|
||||||
|
|
||||||
|
## FastAPI
|
||||||
|
|
||||||
|
!!! info "FastAPI sources"
|
||||||
|
- [Lifespan events](https://fastapi.tiangolo.com/advanced/events/)
|
||||||
|
- [Settings and environment variables](https://fastapi.tiangolo.com/advanced/settings/)
|
||||||
|
- [Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/)
|
||||||
|
- [SQL databases tutorial](https://fastapi.tiangolo.com/tutorial/sql-databases/)
|
||||||
|
|
||||||
|
## SQLAlchemy and Alembic
|
||||||
|
|
||||||
|
!!! info "Persistence sources"
|
||||||
|
- [SQLAlchemy engine configuration and pooling](https://docs.sqlalchemy.org/en/20/core/engines.html)
|
||||||
|
- [SQLAlchemy session lifecycle basics](https://docs.sqlalchemy.org/en/20/orm/session_basics.html)
|
||||||
|
- [Alembic tutorial](https://alembic.sqlalchemy.org/en/latest/tutorial.html)
|
||||||
|
|
||||||
|
## Pydantic
|
||||||
|
|
||||||
|
!!! info "Pydantic source"
|
||||||
|
- [Pydantic settings management](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/)
|
||||||
|
|
||||||
|
## NiceGUI
|
||||||
|
|
||||||
|
!!! info "NiceGUI sources"
|
||||||
|
- [Pages, routing, and FastAPI integration](https://www.nicegui.io/documentation/section_pages_routing)
|
||||||
|
- [Binding properties and bindable dataclass](https://www.nicegui.io/documentation/section_binding_properties)
|
||||||
|
- [Security best practices](https://www.nicegui.io/documentation/section_security)
|
||||||
|
|
||||||
|
## Python Dataclasses
|
||||||
|
|
||||||
|
!!! info "Python sources"
|
||||||
|
- [dataclasses module reference](https://docs.python.org/3/library/dataclasses.html)
|
||||||
|
- [PEP 557: Data Classes](https://peps.python.org/pep-0557/)
|
||||||
|
|
||||||
|
## LangGraph
|
||||||
|
|
||||||
|
!!! info "LangGraph sources"
|
||||||
|
- [Overview](https://docs.langchain.com/oss/python/langgraph/overview)
|
||||||
|
- [Quickstart](https://docs.langchain.com/oss/python/langgraph/quickstart)
|
||||||
|
- [Workflows and agents](https://docs.langchain.com/oss/python/langgraph/workflows-agents)
|
||||||
|
- [Persistence](https://docs.langchain.com/oss/python/langgraph/persistence)
|
||||||
|
- [Memory concepts](https://docs.langchain.com/oss/python/concepts/memory)
|
||||||
|
- [Streaming](https://docs.langchain.com/oss/python/langgraph/streaming)
|
||||||
|
- [Interrupts and human-in-the-loop](https://docs.langchain.com/oss/python/langgraph/interrupts)
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
---
|
||||||
|
name: pydantic-settings
|
||||||
|
description: "Practical guide for implementing typed application configuration with pydantic-settings. Use when designing BaseSettings models, choosing env naming strategy, configuring dotenv or secrets, and customizing source priority safely."
|
||||||
|
x-personal-mcp:
|
||||||
|
id: pydantic-settings
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- python
|
||||||
|
- pydantic
|
||||||
|
- pydantic-settings
|
||||||
|
- configuration
|
||||||
|
- env-vars
|
||||||
|
- secrets
|
||||||
|
- dotenv
|
||||||
|
- source-priority
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/pydantic-settings/document
|
||||||
|
---
|
||||||
|
|
||||||
|
# Pydantic Settings Implementation Guide
|
||||||
|
|
||||||
|
Use this skill to implement robust, typed application configuration with `pydantic-settings` in production Python services.
|
||||||
|
|
||||||
|
## When to Use
|
||||||
|
|
||||||
|
- You need a single typed configuration model for app settings.
|
||||||
|
- You are migrating from ad-hoc `os.getenv(...)` calls.
|
||||||
|
- You need predictable precedence across init args, env vars, dotenv files, and secrets.
|
||||||
|
- You need nested settings models and reliable parsing behavior.
|
||||||
|
- You need to customize settings sources or source order safely.
|
||||||
|
|
||||||
|
## Procedure
|
||||||
|
|
||||||
|
### 1. Baseline Model
|
||||||
|
|
||||||
|
Create a single settings model for the service boundary:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseSettings(BaseModel):
|
||||||
|
host: str = "localhost"
|
||||||
|
port: int = 5432
|
||||||
|
user: str
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_prefix="APP_",
|
||||||
|
env_file=".env",
|
||||||
|
env_file_encoding="utf-8",
|
||||||
|
extra="ignore",
|
||||||
|
)
|
||||||
|
|
||||||
|
debug: bool = False
|
||||||
|
log_level: str = "info"
|
||||||
|
database: DatabaseSettings
|
||||||
|
api_key: str = Field(validation_alias="MY_API_KEY")
|
||||||
|
```
|
||||||
|
|
||||||
|
Quality gate:
|
||||||
|
|
||||||
|
1. Required fields fail fast when missing.
|
||||||
|
2. Defaults are intentional and safe.
|
||||||
|
|
||||||
|
### 2. Pick Env Naming Rules
|
||||||
|
|
||||||
|
1. Choose one prefix and apply it consistently.
|
||||||
|
2. Use aliases only for compatibility or external contracts.
|
||||||
|
3. Document whether env names are case-sensitive.
|
||||||
|
|
||||||
|
Quality gate:
|
||||||
|
|
||||||
|
1. Team can derive env variable names without guessing.
|
||||||
|
2. Legacy names are supported only where needed.
|
||||||
|
|
||||||
|
### 3. Decide Nested Parsing
|
||||||
|
|
||||||
|
For nested models via env vars, configure delimiters intentionally:
|
||||||
|
|
||||||
|
```python
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_prefix="APP_",
|
||||||
|
env_nested_delimiter="__",
|
||||||
|
env_nested_max_split=1,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Typical vars:
|
||||||
|
|
||||||
|
1. `APP_DATABASE={"host": "db", "port": 5432, "user": "svc", "password": "pw"}`
|
||||||
|
2. `APP_DATABASE__HOST=db.internal`
|
||||||
|
|
||||||
|
Quality gate:
|
||||||
|
|
||||||
|
1. Nested overrides behave as expected.
|
||||||
|
2. Delimiter choice does not collide with field names.
|
||||||
|
|
||||||
|
### 4. Confirm Source Priority
|
||||||
|
|
||||||
|
Default priority (higher first):
|
||||||
|
|
||||||
|
1. CLI args (if enabled)
|
||||||
|
2. init kwargs
|
||||||
|
3. env vars
|
||||||
|
4. dotenv
|
||||||
|
5. secrets dir
|
||||||
|
6. defaults
|
||||||
|
|
||||||
|
Only customize when required:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from pydantic_settings import PydanticBaseSettingsSource
|
||||||
|
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def settings_customise_sources(
|
||||||
|
cls,
|
||||||
|
settings_cls: type[BaseSettings],
|
||||||
|
init_settings: PydanticBaseSettingsSource,
|
||||||
|
env_settings: PydanticBaseSettingsSource,
|
||||||
|
dotenv_settings: PydanticBaseSettingsSource,
|
||||||
|
file_secret_settings: PydanticBaseSettingsSource,
|
||||||
|
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||||||
|
return (init_settings, env_settings, dotenv_settings, file_secret_settings)
|
||||||
|
```
|
||||||
|
|
||||||
|
Quality gate:
|
||||||
|
|
||||||
|
1. Priority order is explicit in code.
|
||||||
|
2. Tests verify conflict resolution.
|
||||||
|
|
||||||
|
### 5. Add Secrets Strategy
|
||||||
|
|
||||||
|
1. In local development, dotenv is acceptable for non-production values.
|
||||||
|
2. In deployed environments, prefer env vars or secret managers.
|
||||||
|
3. For file-mounted secrets, use `secrets_dir`.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_prefix="APP_",
|
||||||
|
env_file=".env",
|
||||||
|
secrets_dir="/run/secrets",
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Quality gate:
|
||||||
|
|
||||||
|
1. No secret literals in repository code.
|
||||||
|
2. Missing secrets behavior is understood per environment.
|
||||||
|
|
||||||
|
### 6. Add ContextVar-Scoped Constructors And Accessors
|
||||||
|
|
||||||
|
When configuration and database resources should be request- or context-scoped, use `ContextVar` backed constructor and accessor methods.
|
||||||
|
|
||||||
|
Example pattern:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from contextvars import ContextVar
|
||||||
|
from functools import cache
|
||||||
|
|
||||||
|
from pydantic import SecretStr
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
from sqlmodel import Session, create_engine
|
||||||
|
from sqlalchemy import Engine
|
||||||
|
|
||||||
|
|
||||||
|
class DbSettings(BaseSettings):
|
||||||
|
model_config = {
|
||||||
|
"env_prefix": "DB_",
|
||||||
|
"extra": "ignore",
|
||||||
|
}
|
||||||
|
|
||||||
|
host: str = "localhost"
|
||||||
|
port: int = 5432
|
||||||
|
username: str
|
||||||
|
password: SecretStr
|
||||||
|
|
||||||
|
@property
|
||||||
|
def dsn(self) -> str:
|
||||||
|
return (
|
||||||
|
"postgresql://"
|
||||||
|
f"{self.username}:{self.password.get_secret_value()}"
|
||||||
|
f"@{self.host}:{self.port}/mydatabase"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_db_settings: ContextVar[DbSettings | None] = ContextVar("db_settings", default=None)
|
||||||
|
_db_conn: ContextVar[Engine | None] = ContextVar("db_conn", default=None)
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_settings(**kwargs) -> DbSettings:
|
||||||
|
settings = _db_settings.get()
|
||||||
|
if settings is None:
|
||||||
|
settings = DbSettings(**kwargs)
|
||||||
|
_db_settings.set(settings)
|
||||||
|
cleanup_engine()
|
||||||
|
return settings
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def get_db_engine() -> Engine:
|
||||||
|
engine = _db_conn.get()
|
||||||
|
if engine is None:
|
||||||
|
engine = create_engine(get_db_settings().dsn)
|
||||||
|
_db_conn.set(engine)
|
||||||
|
return engine
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup_engine() -> None:
|
||||||
|
engine = _db_conn.get()
|
||||||
|
if engine is not None:
|
||||||
|
engine.dispose()
|
||||||
|
_db_conn.set(None)
|
||||||
|
get_db_engine.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def get_session():
|
||||||
|
with Session(get_db_engine()) as session:
|
||||||
|
yield session
|
||||||
|
```
|
||||||
|
|
||||||
|
Design notes:
|
||||||
|
|
||||||
|
1. `get_db_settings` is the constructor/accessor for settings and can accept explicit overrides in tests.
|
||||||
|
2. `get_db_engine` is the constructor/accessor for the engine and reuses context-local state.
|
||||||
|
3. `cleanup_engine` must run when settings change so stale DSNs do not leak across contexts.
|
||||||
|
4. `get_session` centralizes session creation so call sites never build engines directly.
|
||||||
|
|
||||||
|
Quality gate:
|
||||||
|
|
||||||
|
1. Overriding settings triggers engine cleanup and cache invalidation.
|
||||||
|
2. No module-level global engine is created outside accessors.
|
||||||
|
3. Session creation always goes through `get_session()`.
|
||||||
|
|
||||||
|
### 7. Add Focused Resource-Lifecycle Test
|
||||||
|
|
||||||
|
Do not add tests that re-validate baseline `pydantic-settings` functionality (for example env parsing, alias semantics, or source precedence) unless you have custom behavior layered on top.
|
||||||
|
|
||||||
|
Minimum test to add (only when an engine accessor exists):
|
||||||
|
|
||||||
|
1. assert the database engine is not instantiated more than once for repeated accessor calls in the same lifecycle/context
|
||||||
|
|
||||||
|
If the project has no database engine accessor, skip this section.
|
||||||
|
|
||||||
|
Suggested invocation:
|
||||||
|
|
||||||
|
1. `uv run pytest -q`
|
||||||
|
|
||||||
|
## Completion Checks
|
||||||
|
|
||||||
|
1. A single typed settings model exists for the service boundary.
|
||||||
|
2. Source precedence is documented and tested.
|
||||||
|
3. Env naming conventions and aliases are explicit and stable.
|
||||||
|
4. Nested parsing behavior is tested when custom parsing behavior is added.
|
||||||
|
5. Secrets and dotenv usage are environment-appropriate and do not leak sensitive defaults.
|
||||||
|
6. Validation errors are actionable and fail fast for required values.
|
||||||
|
7. If an engine accessor exists, engine construction occurs at most once per lifecycle/context.
|
||||||
|
|
||||||
|
## Output Contract
|
||||||
|
|
||||||
|
When this skill is applied, return:
|
||||||
|
|
||||||
|
1. Which references were consulted.
|
||||||
|
2. The chosen source-precedence model and why.
|
||||||
|
3. The exact parsing and alias decisions made.
|
||||||
|
4. Any deferred choices and their risk.
|
||||||
|
5. The validation commands or tests run to confirm behavior.
|
||||||
|
|
||||||
|
Use these upstream docs when implementing or reviewing `pydantic-settings` behavior.
|
||||||
|
|
||||||
|
## Source Docs
|
||||||
|
|
||||||
|
### Primary
|
||||||
|
|
||||||
|
- [Settings Management](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/)
|
||||||
|
- [pydantic-settings package repository](https://github.com/pydantic/pydantic-settings)
|
||||||
|
|
||||||
|
### Core Concepts
|
||||||
|
|
||||||
|
- [Field aliases](https://pydantic.dev/docs/validation/latest/concepts/fields/#field-aliases)
|
||||||
|
- [Alias choices](https://pydantic.dev/docs/validation/latest/concepts/alias#aliaspath-and-aliaschoices)
|
||||||
|
- [Validation default behavior](https://pydantic.dev/docs/validation/latest/concepts/fields#validate-default-values)
|
||||||
|
- [ImportString type](https://pydantic.dev/docs/validation/latest/api/pydantic/types/#pydantic.types.ImportString)
|
||||||
|
|
||||||
|
### Priority And Sources
|
||||||
|
|
||||||
|
- [Field value priority](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#field-value-priority)
|
||||||
|
- [Customise settings sources](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#customise-settings-sources)
|
||||||
|
- [Other settings source types](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#other-settings-source)
|
||||||
|
|
||||||
|
### Environment And Parsing
|
||||||
|
|
||||||
|
- [Environment variable names and prefix behavior](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#environment-variable-names)
|
||||||
|
- [Case sensitivity behavior](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#case-sensitivity)
|
||||||
|
- [Parsing environment variable values](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#parsing-environment-variable-values)
|
||||||
|
- [Nested model default partial updates](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#nested-model-default-partial-updates)
|
||||||
|
|
||||||
|
### Dotenv And Secrets
|
||||||
|
|
||||||
|
- [Dotenv support](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#dotenv-env-support)
|
||||||
|
- [Secrets](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#secrets)
|
||||||
|
- [Nested secrets](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#nested-secrets)
|
||||||
@@ -1,6 +1,19 @@
|
|||||||
---
|
---
|
||||||
name: pytesting
|
name: pytesting
|
||||||
description: "Reference hub for pytest suite structure, naming, markers, and stack-specific testing patterns. Optimized for progressive discovery so naming and hierarchy guidance are loaded first when shaping or reorganizing tests."
|
description: "Reference hub for pytest suite structure, naming, markers, and stack-specific testing patterns. Optimized for progressive discovery so naming and hierarchy guidance are loaded first when shaping or reorganizing tests."
|
||||||
|
x-personal-mcp:
|
||||||
|
id: pytesting
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- pytest
|
||||||
|
- testing
|
||||||
|
- python
|
||||||
|
- fastapi
|
||||||
|
- asyncio
|
||||||
|
- anyio
|
||||||
|
- deterministic
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/pytesting/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# Pytesting
|
# Pytesting
|
||||||
+9
@@ -1,6 +1,15 @@
|
|||||||
---
|
---
|
||||||
name: python-logging
|
name: python-logging
|
||||||
description: 'Design, review, or refactor Python logging. Use when choosing logger names, levels, handlers, library/application boundaries, basicConfig, dictConfig, structured logs, or operational logging defaults.'
|
description: 'Design, review, or refactor Python logging. Use when choosing logger names, levels, handlers, library/application boundaries, basicConfig, dictConfig, structured logs, or operational logging defaults.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: python-logging
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- logging
|
||||||
|
- python
|
||||||
|
- observability
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/python-logging/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# Python Logging
|
# Python Logging
|
||||||
+12
@@ -1,6 +1,18 @@
|
|||||||
---
|
---
|
||||||
name: python-typing
|
name: python-typing
|
||||||
description: "Reference-first skill for reviewing and modernizing Python typing to the newest supported best practices. Use when auditing annotations, replacing legacy typing syntax, and enforcing latest-syntax-first conventions."
|
description: "Reference-first skill for reviewing and modernizing Python typing to the newest supported best practices. Use when auditing annotations, replacing legacy typing syntax, and enforcing latest-syntax-first conventions."
|
||||||
|
x-personal-mcp:
|
||||||
|
id: python-typing
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- python
|
||||||
|
- typing
|
||||||
|
- type-hints
|
||||||
|
- pep-695
|
||||||
|
- modernization
|
||||||
|
- static-analysis
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/python-typing/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# Modern Python Typing Review Reference
|
# Modern Python Typing Review Reference
|
||||||
+11
@@ -1,6 +1,17 @@
|
|||||||
---
|
---
|
||||||
name: ruff-linting-formating
|
name: ruff-linting-formating
|
||||||
description: "Reference-first Ruff skill for repository preferences, baseline defaults, and source links. Use to pick consistent Ruff conventions and integration references, not to run migration playbooks."
|
description: "Reference-first Ruff skill for repository preferences, baseline defaults, and source links. Use to pick consistent Ruff conventions and integration references, not to run migration playbooks."
|
||||||
|
x-personal-mcp:
|
||||||
|
id: ruff-linting-formating
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- ruff
|
||||||
|
- linting
|
||||||
|
- formatting
|
||||||
|
- python
|
||||||
|
- ci
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/ruff-linting-formating/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# Ruff Preferences and References
|
# Ruff Preferences and References
|
||||||
+13
@@ -1,6 +1,19 @@
|
|||||||
---
|
---
|
||||||
name: vscode-configuration
|
name: vscode-configuration
|
||||||
description: 'Create and troubleshoot VS Code workspace configuration for Python projects, with focused patterns for launch.json debugpy/FastAPI debugging and tasks.json task automation.'
|
description: 'Create and troubleshoot VS Code workspace configuration for Python projects, with focused patterns for launch.json debugpy/FastAPI debugging and tasks.json task automation.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: vscode-configuration
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- vscode
|
||||||
|
- launch-json
|
||||||
|
- tasks-json
|
||||||
|
- debugpy
|
||||||
|
- fastapi
|
||||||
|
- python
|
||||||
|
- skills
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/vscode-configuration/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# VS Code Configuration
|
# VS Code Configuration
|
||||||
+17
@@ -1,6 +1,23 @@
|
|||||||
---
|
---
|
||||||
name: zensical-docs
|
name: zensical-docs
|
||||||
description: 'Reference skill for Zensical documentation mechanics. Use for quick lookup of docs structure, feature options, and source links. Prefer inline Markdown links to source docs and avoid bare URLs because this content is rendered as human docs and MCP resources.'
|
description: 'Reference skill for Zensical documentation mechanics. Use for quick lookup of docs structure, feature options, and source links. Prefer inline Markdown links to source docs and avoid bare URLs because this content is rendered as human docs and MCP resources.'
|
||||||
|
x-personal-mcp:
|
||||||
|
id: zensical-docs
|
||||||
|
version: 1.0.0
|
||||||
|
tags:
|
||||||
|
- zensical
|
||||||
|
- mkdocs
|
||||||
|
- mkdocs-material
|
||||||
|
- mkdocstrings
|
||||||
|
- docs
|
||||||
|
- documentation
|
||||||
|
- information-architecture
|
||||||
|
- skills
|
||||||
|
- bootstrap
|
||||||
|
- discovery
|
||||||
|
- authoring
|
||||||
|
capabilities:
|
||||||
|
- resource://skills/zensical-docs/document
|
||||||
---
|
---
|
||||||
|
|
||||||
# Zensical Documentation Authoring
|
# Zensical Documentation Authoring
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user