feat(mcp): initial implementation — MCP server, framework indexer, 10 tools, 8 validation rules (v0.1.0)
Introduces code.nochebuena.dev/einherjar/mcp — the Einherjar Model Context Protocol
server. A remote, streamable-HTTP service that teaches AI assistants about every
other module of the framework: which package exposes which type, what each module
guarantees through its compliance tests, the canonical wiring shape for a service,
and whether a Go snippet follows the conventions. Indexes the framework on disk at
build time and ships a self-contained binary via go:embed; imports nothing from
other einherjar/* modules at compile time.
server (cmd/server):
- Streamable-HTTP MCP server built on github.com/modelcontextprotocol/go-sdk v1.0.0
- mcp.NewServer + mcp.NewStreamableHTTPHandler, served via net/http on EINHERJAR_MCP_ADDR
(default :8080) and EINHERJAR_MCP_PATH (default /mcp)
- /healthz liveness endpoint; structured JSON logging via log/slog
- Loads the embedded data/index.json once at startup; in-memory for the process lifetime
indexer (cmd/indexer):
- Walks an Einherjar repository checkout (default ../), parses every sibling
module's go.mod, README.md, CHANGELOG.md, docs/adr/ADR-*.md, doc.go package
comments, every exported type/interface/func/method/const/var (via go/doc on
go/parser ASTs), and compliance_test.go
- Captures module dependency edges by regex over each go.mod's require lines
(einherjar/* paths only; self-reference filtered)
- Appends a synthetic "wire" module documenting canonical application wiring
conventions, authored at internal/index/builtins/README.md and embedded via
go:embed; participates in list_modules / get_module / get_example like a real module
internal/index:
- Schema einherjar.mcp/index/v1; types: Index, Module, SubPackage, Symbol, ADR,
Example, Compliance, InterfaceAssert, ComplianceTest
- Build(repoRoot) → *Index walks the repo; BuildBuiltins() returns the synthetic
wire module from the embedded markdown
- Load([]byte) → *Index validates the schema version on read
- FindModule, SearchSymbols helpers used by tools
internal/tools (10 tools):
- list_modules — enumerate every module with purpose + sub-packages
- get_module — package doc, dependencies, sub-packages, key symbols, ADRs,
compliance counts; optional embedded README
- search_symbols — full-text across name, doc, sub-package, module; filterable by
module and kind
- get_symbol — full signature, doc comment, source file:line for one symbol
- list_adrs — list ADRs across the framework or within one module
- get_adr — fetch one ADR's markdown body
- get_example — canonical usage snippets extracted from module READMEs and from
the synthetic wire conventions
- get_compliance — interface assertions (var _ Iface = impl) and structural test
names from a module's compliance_test.go
- get_changelog — full CHANGELOG.md markdown for one module
- validate_snippet — pattern-match a Go snippet against framework conventions
internal/rules (8 rules, registered via init() against a single registered slice):
- launcher.missing-run — launcher constructed but Run() never called
- launcher.no-components — launcher.New() called without any .Append(...)
- launcher.run-error-discarded — lc.Run() invoked as an ExprStmt (return ignored)
- logz.direct-env-read — os.Getenv("EINHERJAR_LOG_*") bypassing logz config
- web.server-not-appended — web/server constructed but not added to the launcher
- wire.hook-bad-signature — with<Feature>(...) first param is not launcher.Launcher
- wire.hook-outside-beforestart — repo/service/handler construction or route
registration at the top level of a hook (outside lc.BeforeStart)
- wire.route-specific-after-param — /users/{id} registered before a sibling
/users/me of the same length and method (chi would shadow the literal route)
Synthetic wire module (internal/index/builtins/README.md):
- Project layout (cmd/<app>/main.go + internal/wire/*.go + per-feature domain dirs)
- Canonical Run() shape: config → logger → infra (db, cache, pool, mc, srv) → cross-
cutting (validator, permission provider) → launcher.New → lc.Append(infra...) →
withMigrations / withSuperAdminSeed / withHealth / withFeature hooks → return lc.Run()
- Canonical with<Feature> hook shape: signature (launcher.Launcher first, server.Server
second, deps last), single lc.BeforeStart closure containing all construction +
route registration
- chi route ordering, srv.With(authz(...)) authorization, middleware helpers
(authz / skipPublicPaths / skipMethodPath), tokenSignerAdapter pattern showing
that the framework exposes Signer.Sign as a primitive and the application owns
the access/refresh response shape
Packaging:
- Multi-stage Dockerfile that builds from the einherjar repository root
(docker build -f mcp/Dockerfile .) so cmd/indexer can walk every sibling module
at image-build time; runtime layer is gcr.io/distroless/static-debian12:nonroot
- 86-byte placeholder data/index.json committed once with `git add -f`; subsequent
indexer runs overwrite it locally but the file is .gitignored
- .gitea/CODEOWNERS and pull_request_template.md mirror the sibling layout
Design notes:
- mcp depends on nothing in einherjar/* — it reads the framework via the filesystem
at index time. This keeps mcp outside the framework dependency graph and lets it
index any version of einherjar without versioning itself in lock-step.
- All structured-output tool responses initialise empty slices ([]Type{}) rather
than relying on Go's nil-marshals-to-null default, so the SDK's JSON-schema
output validator never rejects a tools/call result.
This commit is contained in:
1
.gitea/CODEOWNERS
Normal file
1
.gitea/CODEOWNERS
Normal file
@@ -0,0 +1 @@
|
||||
* @einherjar/CoreDevelopers @einherjar/Agents
|
||||
70
.gitea/pull_request_template.md
Normal file
70
.gitea/pull_request_template.md
Normal file
@@ -0,0 +1,70 @@
|
||||
## Summary
|
||||
|
||||
<!-- One or two sentences: what does this PR do and why? -->
|
||||
|
||||
---
|
||||
|
||||
## Type of change
|
||||
|
||||
- [ ] Bug fix — non-breaking change that resolves an issue
|
||||
- [ ] New feature — non-breaking addition of functionality
|
||||
- [ ] Breaking change — alters existing behavior or public API
|
||||
- [ ] Documentation update
|
||||
- [ ] Refactor — no functional change, no new API surface
|
||||
- [ ] Test improvement
|
||||
|
||||
---
|
||||
|
||||
## Description
|
||||
|
||||
<!--
|
||||
Provide enough context for a reviewer who was not in the room:
|
||||
- What problem does this solve?
|
||||
- What approach did you choose, and why?
|
||||
- Were there alternatives you considered and rejected?
|
||||
- Any known limitations or follow-up work?
|
||||
-->
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
- [ ] I added or updated tests that cover my changes
|
||||
- [ ] All tests pass locally — `go test ./...`
|
||||
- [ ] No formatting issues — `gofmt -l .` produces no output
|
||||
- [ ] No vet warnings — `go vet ./...` is clean
|
||||
|
||||
---
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] At most one exported type per non-test `.go` file (CT-6)
|
||||
- [ ] No new external dependencies added without prior discussion in an issue
|
||||
- [ ] Public API changes are reflected in `CHANGELOG.md`
|
||||
- [ ] Breaking changes include a migration note in the PR description above
|
||||
|
||||
---
|
||||
|
||||
## Contributor License Agreement
|
||||
|
||||
> **This PR will not be merged until the CLA comment is present.**
|
||||
|
||||
Before a Maintainer reviews your code, you must post the following text **as a comment on this PR** — not here in the description. PR description checkboxes can be silently toggled by anyone; a comment is a timestamped, author-attributed record that cannot be quietly removed.
|
||||
|
||||
**Copy and post this exact text as a PR comment:**
|
||||
|
||||
---
|
||||
|
||||
> I have read the Einherjar Contributor License Agreement (CLA.md) and I agree to all its terms.
|
||||
> I confirm this Contribution is my original work. I grant the Maintainers the rights described
|
||||
> therein, including the right to relicense, and I retain ownership of my copyright.
|
||||
> This agreement covers all future Contributions I submit to any Einherjar repository under
|
||||
> this account.
|
||||
|
||||
---
|
||||
|
||||
First time contributing? Read [CLA.md](../CLA.md) for the full agreement before posting the comment.
|
||||
|
||||
If you are contributing on behalf of a company, an authorized representative of that company must post the comment.
|
||||
|
||||
<!-- Thank you for contributing to Einherjar. For those who come after. -->
|
||||
41
.gitignore
vendored
Normal file
41
.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
# ── Release workflow helpers ──────────────────────────────────────────────────
|
||||
COMMIT.md
|
||||
PR.md
|
||||
RELEASE.md
|
||||
|
||||
# ── Go build artifacts ────────────────────────────────────────────────────────
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
*.test
|
||||
*.out
|
||||
/dist/
|
||||
/bin/
|
||||
|
||||
# ── Go workspace (local development only) ────────────────────────────────────
|
||||
go.work
|
||||
go.work.sum
|
||||
|
||||
# ── Dependency vendor directory ───────────────────────────────────────────────
|
||||
vendor/
|
||||
|
||||
# ── Coverage output ───────────────────────────────────────────────────────────
|
||||
coverage.out
|
||||
coverage.html
|
||||
*.coverprofile
|
||||
|
||||
# ── OS artifacts ─────────────────────────────────────────────────────────────
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# ── Editor artifacts ──────────────────────────────────────────────────────────
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# ── Generated framework index (rebuilt by cmd/indexer; placeholder is committed) ─
|
||||
data/index.json
|
||||
57
CHANGELOG.md
Normal file
57
CHANGELOG.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# Changelog — einherjar/mcp
|
||||
|
||||
All notable changes to this module are documented here.
|
||||
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
---
|
||||
|
||||
## [0.1.0] — 2026-05-29
|
||||
|
||||
Initial release. The `mcp` module hosts the **Einherjar Model Context Protocol server** — a remote, streamable-HTTP service that teaches AI assistants about every other module of the framework.
|
||||
|
||||
### Added
|
||||
|
||||
#### Server (`cmd/server`)
|
||||
|
||||
- Streamable-HTTP MCP server built on `github.com/modelcontextprotocol/go-sdk` v1.0.0
|
||||
- Listen address and HTTP path configurable via `EINHERJAR_MCP_ADDR` (default `:8080`) and `EINHERJAR_MCP_PATH` (default `/mcp`)
|
||||
- `/healthz` liveness endpoint
|
||||
- Embedded framework index loaded once at startup; in-memory for the lifetime of the process
|
||||
|
||||
#### Indexer (`cmd/indexer`)
|
||||
|
||||
- Walks an Einherjar repository checkout and produces `data/index.json`
|
||||
- For each sibling module captures: import path, Go version, README (full + extracted tagline), CHANGELOG, root `doc.go` package comment, sub-package doc comments, every exported symbol (type/interface/func/method/const/var) with signature + godoc, ADRs, README code-fence examples, dependency edges from `go.mod`, and the contents of `compliance_test.go` (interface assertions + structural test names)
|
||||
- Appends a synthetic `wire` module documenting canonical Einherjar application wiring conventions
|
||||
|
||||
#### Tools (10)
|
||||
|
||||
- `list_modules` — enumerate every Einherjar module with purpose and sub-packages
|
||||
- `get_module` — package doc, dependencies, sub-packages, key symbols, ADRs, compliance counts; optional embedded README
|
||||
- `search_symbols` — full-text search across name, doc, sub-package, module
|
||||
- `get_symbol` — full signature, doc, and source location for one symbol
|
||||
- `list_adrs` — list architectural decision records, optionally filtered by module
|
||||
- `get_adr` — fetch one ADR's markdown body
|
||||
- `get_example` — canonical usage snippets extracted from module READMEs and the `wire` conventions
|
||||
- `get_compliance` — interface assertions and structural test names from a module's `compliance_test.go`
|
||||
- `get_changelog` — full CHANGELOG.md markdown for one module
|
||||
- `validate_snippet` — pattern-match a Go snippet against framework conventions; returns findings with severity, hint, and line
|
||||
|
||||
#### Validation rules (8)
|
||||
|
||||
- `launcher.missing-run`, `launcher.no-components`, `launcher.run-error-discarded`
|
||||
- `logz.direct-env-read`
|
||||
- `web.server-not-appended`
|
||||
- `wire.hook-bad-signature`, `wire.hook-outside-beforestart`, `wire.route-specific-after-param`
|
||||
|
||||
#### Synthetic `wire` module
|
||||
|
||||
- Authored in `internal/index/builtins/README.md`; participates in `list_modules`, `get_module`, and `get_example` exactly like a real module
|
||||
- Sections: project layout, `Run()` shape, feature hook shape, route ordering, authorization, middleware helpers, adapters at the wire boundary, migrations and seeds
|
||||
- All examples use einherjar import paths
|
||||
|
||||
#### Packaging
|
||||
|
||||
- Multi-stage `Dockerfile` that builds from the einherjar repository root (`docker build -f mcp/Dockerfile .`) so the indexer can walk every sibling module at image-build time
|
||||
- Distroless runtime image; static binary; non-root user
|
||||
90
CLA.md
Normal file
90
CLA.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Contributor License Agreement
|
||||
|
||||
By contributing to any Einherjar repository, you agree to the terms of this Contributor License Agreement ("Agreement"). Please read it carefully before submitting your first Pull Request.
|
||||
|
||||
---
|
||||
|
||||
## 1. Definitions
|
||||
|
||||
| Term | Meaning |
|
||||
|---|---|
|
||||
| **You** | The individual or legal entity submitting a Contribution |
|
||||
| **Contribution** | Any original work — source code, documentation, tests, configuration — submitted to an Einherjar repository |
|
||||
| **Project** | The Einherjar framework and all repositories under `code.nochebuena.dev/einherjar/` |
|
||||
| **Maintainers** | The individuals responsible for maintaining the Project |
|
||||
|
||||
---
|
||||
|
||||
## 2. You Retain Ownership
|
||||
|
||||
This Agreement does **not** transfer your copyright to the Maintainers. You remain the legal owner of your Contribution. What you grant here is a broad license to use it — not ownership of it.
|
||||
|
||||
---
|
||||
|
||||
## 3. Copyright License Grant
|
||||
|
||||
You grant the Maintainers and all recipients of the Project a **perpetual, worldwide, non-exclusive, royalty-free, irrevocable** license to:
|
||||
|
||||
- Reproduce, modify, and create derivative works of your Contribution
|
||||
- Publicly display and perform your Contribution
|
||||
- Distribute your Contribution and derivative works, in source or compiled form, under any terms
|
||||
- Sublicense the above rights to third parties
|
||||
- **Relicense** your Contribution under a different open-source or commercial license at the Maintainers' sole discretion
|
||||
|
||||
The Maintainers commit to keeping the Project available under at least one OSI-approved open-source license at all times.
|
||||
|
||||
---
|
||||
|
||||
## 4. Patent License Grant
|
||||
|
||||
You grant the Maintainers and all recipients of the Project a **perpetual, worldwide, non-exclusive, royalty-free, irrevocable** patent license to make, use, sell, offer for sale, import, and distribute your Contribution — limited to patent claims you own or control that are necessarily infringed by your Contribution alone, or in combination with the Project to which you submitted it.
|
||||
|
||||
---
|
||||
|
||||
## 5. Your Representations
|
||||
|
||||
By submitting a Contribution, you confirm that:
|
||||
|
||||
1. **Original work.** The Contribution is your original work, or you have the legal right to submit it under these terms.
|
||||
2. **No infringement.** To your knowledge, the Contribution does not infringe any third-party intellectual property rights, including patents, copyrights, and trade secrets.
|
||||
3. **Employer rights.** If your employer holds rights over intellectual property you create, you have obtained written permission to submit the Contribution on behalf of that employer, or your employer has explicitly waived such rights for contributions to open-source projects.
|
||||
4. **No warranty implied.** You understand that your Contribution may or may not be included in the Project, and the Maintainers are under no obligation to use it.
|
||||
|
||||
---
|
||||
|
||||
## 6. No Support Obligation
|
||||
|
||||
You are not required to provide maintenance, support, or updates for your Contributions. They are accepted **"as-is"**, without any warranty of fitness for a particular purpose or correctness.
|
||||
|
||||
---
|
||||
|
||||
## 7. How to Sign
|
||||
|
||||
Consent is given by **posting a comment** on your Pull Request with the following exact text:
|
||||
|
||||
```
|
||||
I have read the Einherjar Contributor License Agreement (CLA.md) and I agree to all its terms.
|
||||
I confirm this Contribution is my original work. I grant the Maintainers the rights described
|
||||
therein, including the right to relicense, and I retain ownership of my copyright.
|
||||
This agreement covers all future Contributions I submit to any Einherjar repository under
|
||||
this account.
|
||||
```
|
||||
|
||||
**Why a comment and not a checkbox?**
|
||||
PR description checkboxes can be silently toggled on and off by anyone with write access to the branch at any time. A comment creates a timestamped, author-attributed record in the PR activity log — it cannot be quietly retracted. If a comment is deleted, the deletion itself is visible in the activity log.
|
||||
|
||||
No handwritten or electronic signature is required beyond the comment above. A Maintainer will verify the comment before merging. PRs without the comment will not be merged.
|
||||
|
||||
If you are contributing on behalf of a company or organization, ensure that an authorized representative of that entity has reviewed and accepted these terms before submitting. The comment must be posted by the account that owns the Contribution.
|
||||
|
||||
---
|
||||
|
||||
## 8. Governing Terms
|
||||
|
||||
This Agreement is intended to be simple and broadly fair. It follows the model established by widely adopted CLAs from the Apache Software Foundation, Google, and MongoDB — granting the Project the flexibility to evolve while fully preserving your ownership of what you wrote.
|
||||
|
||||
If any provision of this Agreement is found unenforceable, the remaining provisions continue in full effect.
|
||||
|
||||
---
|
||||
|
||||
*For those who come after. — The Einherjar Maintainers*
|
||||
247
CONTRIBUTING.md
Normal file
247
CONTRIBUTING.md
Normal file
@@ -0,0 +1,247 @@
|
||||
# Contributing to Einherjar
|
||||
|
||||
Thank you for your interest in contributing to Einherjar. This document explains everything you need to know before sending your first Pull Request.
|
||||
|
||||
Einherjar is developed and maintained by **NOCHEBUENADEV**, the trade name of its founder operating as a *Persona Física con Actividad Empresarial* (PFAE) under Mexican law. Contributions are welcome and valued — but they are accepted under the terms described here, so please read this document fully before you begin.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Before You Start](#1-before-you-start)
|
||||
2. [Legal: CLA and Copyright](#2-legal-cla-and-copyright)
|
||||
3. [Development Setup](#3-development-setup)
|
||||
4. [Code Standards](#4-code-standards)
|
||||
5. [Commit Messages](#5-commit-messages)
|
||||
6. [Submitting a Pull Request](#6-submitting-a-pull-request)
|
||||
7. [Reporting Bugs](#7-reporting-bugs)
|
||||
8. [Requesting Features](#8-requesting-features)
|
||||
9. [What Gets Accepted](#9-what-gets-accepted)
|
||||
|
||||
---
|
||||
|
||||
## 1. Before You Start
|
||||
|
||||
**Open an issue first for anything non-trivial.**
|
||||
|
||||
Before you write a line of code, open an issue describing what you want to change and why. This protects your time: a change that seems straightforward may conflict with a planned refactor, an architectural decision, or the project's direction. Getting alignment before coding means your PR will not be rejected for reasons unrelated to its quality.
|
||||
|
||||
Exceptions where you can skip the issue:
|
||||
- Typo or documentation-only fix
|
||||
- Test coverage improvement for existing behavior
|
||||
- Trivially obvious bug with a clear, contained fix
|
||||
|
||||
**Do not submit a PR that changes the public API of any module without prior discussion.** Every Einherjar module has a stability contract. Breaking changes require a major version bump and coordinated updates across dependent modules.
|
||||
|
||||
---
|
||||
|
||||
## 2. Legal: CLA and Copyright
|
||||
|
||||
### Contributor License Agreement
|
||||
|
||||
Before your first PR can be merged, you must sign the Contributor License Agreement by **posting a specific comment** on your Pull Request. The required comment text and full instructions are in [CLA.md](CLA.md).
|
||||
|
||||
> Checkboxes in PR descriptions are not used for CLA consent — they can be silently toggled by anyone. A comment is a timestamped, author-attributed record.
|
||||
|
||||
### Copyright
|
||||
|
||||
All original code in Einherjar is copyright **NOCHEBUENADEV**. NOCHEBUENADEV is the registered trade name of its founder, a natural person operating under the Mexican *Persona Física con Actividad Empresarial* (PFAE) regime.
|
||||
|
||||
When you contribute, you retain ownership of what you wrote. By signing the CLA you grant NOCHEBUENADEV a perpetual, irrevocable, worldwide license to use, modify, sublicense, and redistribute your Contribution — including the right to relicense it. See [CLA.md](CLA.md) for the full terms.
|
||||
|
||||
### License
|
||||
|
||||
Einherjar is licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0). Your Contributions will be distributed under the same license unless the Maintainers exercise their relicensing rights under the CLA.
|
||||
|
||||
---
|
||||
|
||||
## 3. Development Setup
|
||||
|
||||
Einherjar uses a Go workspace (`go.work`) that spans all modules. You do not need to `go get` anything — local replacements are wired automatically.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Go 1.26+
|
||||
- Git
|
||||
|
||||
### Clone and initialize
|
||||
|
||||
```bash
|
||||
git clone https://code.nochebuena.dev/einherjar/<module-name>
|
||||
cd <module-name>
|
||||
|
||||
# If working across multiple modules, clone the workspace root instead
|
||||
# and all modules will resolve from disk via go.work.
|
||||
```
|
||||
|
||||
### Verify your setup
|
||||
|
||||
```bash
|
||||
go build ./... # must compile clean
|
||||
go vet ./... # no warnings
|
||||
go test ./... # all tests pass
|
||||
gofmt -l . # no output (no unformatted files)
|
||||
```
|
||||
|
||||
All four commands must produce clean output before a PR will be reviewed.
|
||||
|
||||
---
|
||||
|
||||
## 4. Code Standards
|
||||
|
||||
These are non-negotiable. Every PR is checked against them.
|
||||
|
||||
### One exported type per file (CT-6)
|
||||
|
||||
Each non-test `.go` file may contain **at most one exported TypeSpec** (type, struct, or interface declaration). Unexported helpers, constants, and functions may coexist in the same file. `_test.go` files are exempt.
|
||||
|
||||
This rule exists to keep the codebase navigable: a developer who knows the type name can immediately predict the file name.
|
||||
|
||||
```
|
||||
provider.go ← type Provider interface { ... } ✓ one exported type
|
||||
component.go ← type Component interface { ... } ✓ one exported type
|
||||
new.go ← func New(...) + unexported impl ✓ zero exported types
|
||||
```
|
||||
|
||||
### Formatting
|
||||
|
||||
All code must be formatted with `gofmt`. No exceptions. If `gofmt -l .` produces output, the PR will not be merged.
|
||||
|
||||
Do not configure your editor to use `goimports` as a replacement — it may add import groups that diverge from the project style. Use `gofmt` + manual import management.
|
||||
|
||||
### Naming conventions
|
||||
|
||||
- Follow standard Go naming: `CamelCase` for exported, `camelCase` for unexported.
|
||||
- Interfaces that represent a capability are named with an agent noun: `Provider`, `Sender`, `Checkable`.
|
||||
- Interfaces that represent a full component are named `Component`.
|
||||
- Config structs are named `Config`. One config struct per module root.
|
||||
- Constructors are named `New` (main) or `NewXxx` (adapters and variants).
|
||||
|
||||
### Error handling
|
||||
|
||||
- Use `core/xerrors` for all errors returned from public API. Never return raw `errors.New` or `fmt.Errorf` from exported functions.
|
||||
- Error codes must map to the gRPC canonical set defined in `xerrors`. If you need a new code, open an issue first.
|
||||
- Do not swallow errors silently. Log at the appropriate level or return them.
|
||||
|
||||
### No comments unless necessary
|
||||
|
||||
Do not add comments that restate what the code already says. Only add a comment when the **why** is non-obvious: a hidden constraint, a subtle invariant, a workaround for a known upstream bug. If removing the comment would not confuse a future reader, do not write it.
|
||||
|
||||
### Dependencies
|
||||
|
||||
Do not add new external dependencies without opening an issue and getting explicit approval first. Einherjar modules are deliberately lean. Every new dependency increases the blast radius for downstream consumers.
|
||||
|
||||
---
|
||||
|
||||
## 5. Commit Messages
|
||||
|
||||
Follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:
|
||||
|
||||
```
|
||||
<type>(<scope>): <short description>
|
||||
|
||||
[optional body]
|
||||
```
|
||||
|
||||
| Type | When to use |
|
||||
|---|---|
|
||||
| `feat` | New exported function, type, or behavior |
|
||||
| `fix` | Bug fix in existing behavior |
|
||||
| `docs` | Documentation only |
|
||||
| `test` | Tests only, no production code change |
|
||||
| `refactor` | Code restructure with no behavior change |
|
||||
| `chore` | Build system, CI, dependency updates |
|
||||
|
||||
**Scope** is the module name without the `einherjar/` prefix: `core`, `web`, `db-postgres`, `cache-valkey`, etc.
|
||||
|
||||
Examples:
|
||||
```
|
||||
feat(cache-valkey): add IncrWithTTL for atomic fixed-window counters
|
||||
fix(db-postgres): handle pgconn deadline exceeded as ErrDeadlineExceeded
|
||||
docs(web): document rate limiter fail-open behavior
|
||||
```
|
||||
|
||||
Keep the subject line under 72 characters. Write in the imperative mood ("add", "fix", "remove" — not "added", "fixes", "removed").
|
||||
|
||||
---
|
||||
|
||||
## 6. Submitting a Pull Request
|
||||
|
||||
1. **Open an issue first** (see §1) unless the change is trivial.
|
||||
2. Fork the repository and create a branch from `main`:
|
||||
```bash
|
||||
git checkout -b feat/your-feature-name
|
||||
```
|
||||
3. Make your changes following the standards in §4.
|
||||
4. Ensure all verification commands pass (§3).
|
||||
5. Open the PR against `main` using the provided PR template.
|
||||
6. **Post the CLA comment** on the PR before requesting review (see §2 and [CLA.md](CLA.md)).
|
||||
7. Respond to review feedback. Keep the review cycle short by addressing all comments before re-requesting review.
|
||||
|
||||
### Branch naming
|
||||
|
||||
| Prefix | Use for |
|
||||
|---|---|
|
||||
| `feat/` | New features |
|
||||
| `fix/` | Bug fixes |
|
||||
| `docs/` | Documentation changes |
|
||||
| `test/` | Test additions or improvements |
|
||||
| `refactor/` | Refactors without behavior change |
|
||||
|
||||
### PR size
|
||||
|
||||
Keep PRs focused. A PR that does one thing is easier to review, faster to merge, and safer to revert if needed. If your change naturally spans multiple concerns, split it into multiple PRs.
|
||||
|
||||
---
|
||||
|
||||
## 7. Reporting Bugs
|
||||
|
||||
Open an issue with the following information:
|
||||
|
||||
- **Module** affected (`einherjar/db-postgres`, `einherjar/web`, etc.)
|
||||
- **Go version** (`go version`)
|
||||
- **Minimal reproduction** — the smallest code snippet that demonstrates the problem
|
||||
- **Expected behavior** vs **actual behavior**
|
||||
- **Error output** if applicable (sanitize any credentials or sensitive data)
|
||||
|
||||
Do not open a PR to fix a bug without first opening an issue. The bug may be intentional behavior, already fixed on `main`, or caused by something outside the module.
|
||||
|
||||
---
|
||||
|
||||
## 8. Requesting Features
|
||||
|
||||
Open an issue with:
|
||||
|
||||
- **What** you want to add and **why** it belongs in the framework (not in application code)
|
||||
- **Which module** it affects, or whether it requires a new module
|
||||
- **API sketch** — what the interface, function signature, or config field would look like
|
||||
- **Alternative approaches** you considered
|
||||
|
||||
Feature requests that add a new external dependency, change a public interface, or cross module boundaries require longer discussion before approval.
|
||||
|
||||
---
|
||||
|
||||
## 9. What Gets Accepted
|
||||
|
||||
Einherjar is a **focused framework**. It covers a specific, well-defined set of infrastructure concerns. Contributions that fall outside that scope — however well-written — will not be merged.
|
||||
|
||||
What fits:
|
||||
- Bug fixes in existing behavior
|
||||
- Performance improvements with benchmarks
|
||||
- Missing error mappings for existing drivers
|
||||
- Documentation improvements and example corrections
|
||||
- Test coverage for untested edge cases
|
||||
|
||||
What does not fit without prior architectural agreement:
|
||||
- New modules (open an issue first)
|
||||
- New external dependencies
|
||||
- Changes to public interfaces in any module
|
||||
- Features that belong in application code rather than the framework
|
||||
|
||||
If you are unsure, open an issue and ask. It costs nothing and saves everyone time.
|
||||
|
||||
---
|
||||
|
||||
*Einherjar was built for those who come after. Contributions that hold to that standard — clear, documented, tested, designed for the developer who was never in the room — are always welcome.*
|
||||
|
||||
— **NOCHEBUENADEV**
|
||||
16
Dockerfile
Normal file
16
Dockerfile
Normal file
@@ -0,0 +1,16 @@
|
||||
FROM golang:1.26-alpine AS build
|
||||
WORKDIR /src
|
||||
|
||||
# The build context must include the indexer's input: the entire Einherjar
|
||||
# repository. Build from the repo root with -f mcp/Dockerfile.
|
||||
COPY . .
|
||||
|
||||
WORKDIR /src/mcp
|
||||
RUN go mod download
|
||||
RUN go run ./cmd/indexer /src
|
||||
RUN CGO_ENABLED=0 go build -o /out/einherjar-mcp ./cmd/server
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=build /out/einherjar-mcp /einherjar-mcp
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/einherjar-mcp"]
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
171
README.md
Normal file
171
README.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# einherjar/mcp
|
||||
|
||||
[](https://code.nochebuena.dev/einherjar/mcp)
|
||||
[](LICENSE)
|
||||
[](https://go.dev)
|
||||
|
||||
> Every warrior who knew the sagas had a skald nearby. This is yours.
|
||||
|
||||
`code.nochebuena.dev/einherjar/mcp` is the Einherjar **Model Context Protocol** server.
|
||||
It is a remote, streamable-HTTP service that teaches AI assistants about every other
|
||||
module of the framework: which package exposes which type, what each module promises
|
||||
via its compliance tests, the canonical wiring shape for a service, and whether a
|
||||
snippet of Go follows the conventions. Anyone who works in an Einherjar codebase can
|
||||
point their AI tools at one URL and get answers grounded in the actual source.
|
||||
|
||||
---
|
||||
|
||||
## What Is Einherjar?
|
||||
|
||||
In Norse mythology, the Einherjar are the chosen warriors of Valhalla — selected not
|
||||
for glory, but to be ready for what comes after. They train. They prepare. They build
|
||||
the capability that others will rely on.
|
||||
|
||||
This framework is named for that purpose. Every module is a piece of that preparation:
|
||||
built carefully, documented for those who were never in the room, and designed to hold
|
||||
under pressure.
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---|---|
|
||||
| `cmd/server` | Streamable-HTTP MCP server. Embeds the framework index at build time and serves it over a single HTTP endpoint. |
|
||||
| `cmd/indexer` | Walks an Einherjar repository checkout and writes the framework index to `data/index.json`. |
|
||||
|
||||
---
|
||||
|
||||
## Tools
|
||||
|
||||
The server exposes **ten** tools to MCP-aware clients (Claude desktop, Claude Code,
|
||||
Cursor, Zed, and anything else that speaks MCP):
|
||||
|
||||
| Tool | Purpose |
|
||||
|---|---|
|
||||
| `list_modules` | Enumerate every Einherjar module with its purpose and sub-packages |
|
||||
| `get_module` | Package doc, dependencies, sub-packages, key types, compliance counts; optional README |
|
||||
| `search_symbols` | Find a type, function, or interface by name, doc text, sub-package, or module |
|
||||
| `get_symbol` | Full signature, doc comment, and source location for one symbol |
|
||||
| `list_adrs` | List architectural decision records, optionally restricted to one module |
|
||||
| `get_adr` | Fetch a single ADR's markdown body |
|
||||
| `get_example` | Canonical usage snippet — pulled from module READMEs and from the synthetic `wire` conventions |
|
||||
| `get_compliance` | Interface assertions and structural test names from a module's `compliance_test.go` |
|
||||
| `get_changelog` | Full `CHANGELOG.md` markdown for one module |
|
||||
| `validate_snippet` | Pattern-match a Go snippet against framework conventions; returns findings with severity, hint, and line |
|
||||
|
||||
`validate_snippet` ships **eight** wiring-convention rules at v0.1.0:
|
||||
`launcher.missing-run`, `launcher.no-components`, `launcher.run-error-discarded`,
|
||||
`logz.direct-env-read`, `web.server-not-appended`, `wire.hook-bad-signature`,
|
||||
`wire.hook-outside-beforestart`, and `wire.route-specific-after-param`.
|
||||
|
||||
---
|
||||
|
||||
## Build Flow
|
||||
|
||||
```
|
||||
build time runtime
|
||||
┌──────────────────────────────┐ ┌──────────────────────────┐
|
||||
│ cmd/indexer ../ │ │ cmd/server │
|
||||
│ walks every Einherjar │ │ streamable-HTTP MCP │
|
||||
│ module, parses Go pkgs, │ ──▶ │ tools served from the │
|
||||
│ reads READMEs + ADRs │ │ embedded index.json │
|
||||
│ ⇒ data/index.json (embed) │ │ │
|
||||
└──────────────────────────────┘ └──────────────────────────┘
|
||||
```
|
||||
|
||||
The indexer is a separate command. It produces `data/index.json` which the server
|
||||
embeds via `//go:embed`, so the deployed binary is self-contained and reads nothing
|
||||
from disk at runtime.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
### Local run
|
||||
|
||||
```bash
|
||||
# 1. Build the framework index from the sibling Einherjar modules
|
||||
go run ./cmd/indexer ..
|
||||
|
||||
# 2. Build and run the server
|
||||
go build -o bin/einherjar-mcp ./cmd/server
|
||||
./bin/einherjar-mcp -addr :8080 -path /mcp
|
||||
```
|
||||
|
||||
### Container
|
||||
|
||||
```bash
|
||||
# Build the image from the einherjar repo root so the indexer can walk every
|
||||
# sibling module at image-build time.
|
||||
docker build -f mcp/Dockerfile -t einherjar-mcp:0.1.0 .
|
||||
|
||||
docker run --rm -p 8080:8080 einherjar-mcp:0.1.0
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
| Variable | Default | Effect |
|
||||
|---|---|---|
|
||||
| `EINHERJAR_MCP_ADDR` | `:8080` | Listen address for the MCP server |
|
||||
| `EINHERJAR_MCP_PATH` | `/mcp` | HTTP path served by the streamable-HTTP endpoint |
|
||||
|
||||
---
|
||||
|
||||
## Wiring Conventions (the synthetic `wire` module)
|
||||
|
||||
The MCP server ships a 15th, **synthetic** module called `wire`. It is not an
|
||||
Einherjar module — it documents the canonical *application* shape that uses Einherjar
|
||||
modules. The content lives at `internal/index/builtins/README.md` and is embedded at
|
||||
build time. AI assistants discover it via `list_modules` and read it via `get_module`
|
||||
and `get_example` the same way they read any real module.
|
||||
|
||||
The conventions captured: project layout (`cmd/<app>/main.go`, `internal/wire/*.go`,
|
||||
domain layout per feature), the fixed shape of `Run()`, the fixed shape of a
|
||||
`with<Feature>` hook (one `lc.BeforeStart` containing all construction and route
|
||||
registration), route-ordering rules for chi, the `authz` middleware helper, when to
|
||||
use `skipPublicPaths` vs `skipMethodPath`, and adapter patterns at the wire boundary.
|
||||
|
||||
---
|
||||
|
||||
## Dependency Rules
|
||||
|
||||
```
|
||||
contracts (zero dependencies)
|
||||
↑
|
||||
core, web, auth, … (every framework module)
|
||||
↑
|
||||
mcp (reads framework source at index-time only)
|
||||
```
|
||||
|
||||
`mcp` imports **nothing** from other Einherjar modules at compile time. The indexer
|
||||
parses the framework source on disk and writes a JSON blob; the server embeds that
|
||||
blob. This keeps `mcp` outside the framework dependency graph: it can index any
|
||||
version of einherjar without versioning itself in lock-step.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
cd mcp/
|
||||
go build ./... # must compile clean
|
||||
go vet ./... # no warnings
|
||||
go test ./... # all tests pass
|
||||
gofmt -l . # no output
|
||||
```
|
||||
|
||||
All four commands must produce clean output before a PR will be reviewed.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
No ADRs at `v0.1.0`. The structural decisions in this release (synthetic `wire`
|
||||
module, `go:embed` of the index, build-time-not-runtime knowledge model, primitives
|
||||
not response shapes) are captured in the framework-wide memory and in this README.
|
||||
|
||||
---
|
||||
|
||||
> *A blade is sharper when the warrior knows its name.*
|
||||
> *This is what tells them.*
|
||||
55
cmd/indexer/main.go
Normal file
55
cmd/indexer/main.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// Command indexer walks an Einherjar repository checkout, parses every
|
||||
// sibling module, and writes the resulting framework knowledge index to
|
||||
// data/index.json (or the path given by -out).
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// go run ./cmd/indexer .. # default output: data/index.json
|
||||
// go run ./cmd/indexer -out idx.json /path/to/einherjar
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
)
|
||||
|
||||
func main() {
|
||||
out := flag.String("out", "data/index.json", "output path for the generated index")
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "usage: indexer [-out path] <einherjar-repo-root>\n")
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
flag.Parse()
|
||||
|
||||
root := flag.Arg(0)
|
||||
if root == "" {
|
||||
root = ".."
|
||||
}
|
||||
|
||||
idx, err := index.Build(root)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "indexer: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
idx.Modules = append(idx.Modules, index.BuildBuiltins())
|
||||
|
||||
f, err := os.Create(*out)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "indexer: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
enc := json.NewEncoder(f)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(idx); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "indexer: encode: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "indexer: wrote %s (%d modules)\n", *out, len(idx.Modules))
|
||||
}
|
||||
69
cmd/server/main.go
Normal file
69
cmd/server/main.go
Normal file
@@ -0,0 +1,69 @@
|
||||
// Command server is the Einherjar MCP server: a streamable-HTTP service
|
||||
// exposing framework knowledge tools to AI assistants.
|
||||
//
|
||||
// The framework index is embedded into the binary at build time by
|
||||
// cmd/indexer. The server itself only reads it.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
mcpmod "code.nochebuena.dev/einherjar/mcp"
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/tools"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
const (
|
||||
serverName = "einherjar-mcp"
|
||||
serverVersion = "v0.1.0"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := flag.String("addr", envOr("EINHERJAR_MCP_ADDR", ":8080"), "listen address")
|
||||
path := flag.String("path", envOr("EINHERJAR_MCP_PATH", "/mcp"), "HTTP path for the MCP streamable endpoint")
|
||||
flag.Parse()
|
||||
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||
|
||||
idx, err := index.Load(mcpmod.IndexJSON)
|
||||
if err != nil {
|
||||
log.Error("load index", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Info("index loaded", "modules", len(idx.Modules), "builtAt", idx.BuiltAt)
|
||||
|
||||
server := mcp.NewServer(&mcp.Implementation{
|
||||
Name: serverName,
|
||||
Version: serverVersion,
|
||||
}, nil)
|
||||
tools.Register(server, idx)
|
||||
|
||||
handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server {
|
||||
return server
|
||||
}, nil)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle(*path, handler)
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
|
||||
fmt.Fprintln(w, "ok")
|
||||
})
|
||||
|
||||
log.Info("listening", "addr", *addr, "path", *path)
|
||||
if err := http.ListenAndServe(*addr, mux); err != nil {
|
||||
log.Error("server", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func envOr(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
9
data.go
Normal file
9
data.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package mcp
|
||||
|
||||
import _ "embed"
|
||||
|
||||
// IndexJSON is the framework knowledge index, produced by cmd/indexer and
|
||||
// embedded into the server binary at build time.
|
||||
//
|
||||
//go:embed data/index.json
|
||||
var IndexJSON []byte
|
||||
1
data/index.json
Normal file
1
data/index.json
Normal file
@@ -0,0 +1 @@
|
||||
{"schema":"einherjar.mcp/index/v1","framework":"einherjar","builtAt":"","modules":[]}
|
||||
17
doc.go
Normal file
17
doc.go
Normal file
@@ -0,0 +1,17 @@
|
||||
// Package mcp hosts the Einherjar Model Context Protocol server: a remote
|
||||
// streamable-HTTP service that gives AI assistants accurate, structured
|
||||
// knowledge about the Einherjar framework.
|
||||
//
|
||||
// The server exposes tools for browsing modules, looking up symbols and
|
||||
// architectural decision records, fetching canonical examples, and validating
|
||||
// user code against framework conventions. Knowledge is built at deploy time
|
||||
// by cmd/indexer (which walks the sibling Einherjar modules) and embedded
|
||||
// into the server binary as a JSON index.
|
||||
//
|
||||
// Sub-packages:
|
||||
// - cmd/server — streamable HTTP MCP server entry point
|
||||
// - cmd/indexer — produces data/index.json from a local Einherjar checkout
|
||||
// - internal/index — index types and embedded loader
|
||||
// - internal/tools — one file per MCP tool
|
||||
// - internal/rules — lightweight pattern-match rules for validate_snippet
|
||||
package mcp
|
||||
10
go.mod
Normal file
10
go.mod
Normal file
@@ -0,0 +1,10 @@
|
||||
module code.nochebuena.dev/einherjar/mcp
|
||||
|
||||
go 1.26
|
||||
|
||||
require github.com/modelcontextprotocol/go-sdk v1.0.0
|
||||
|
||||
require (
|
||||
github.com/google/jsonschema-go v0.3.0 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
)
|
||||
10
go.sum
Normal file
10
go.sum
Normal file
@@ -0,0 +1,10 @@
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/jsonschema-go v0.3.0 h1:6AH2TxVNtk3IlvkkhjrtbUc4S8AvO0Xii0DxIygDg+Q=
|
||||
github.com/google/jsonschema-go v0.3.0/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/modelcontextprotocol/go-sdk v1.0.0 h1:Z4MSjLi38bTgLrd/LjSmofqRqyBiVKRyQSJgw8q8V74=
|
||||
github.com/modelcontextprotocol/go-sdk v1.0.0/go.mod h1:nYtYQroQ2KQiM0/SbyEPUWQ6xs4B95gJjEalc9AQyOs=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
415
internal/index/builder.go
Normal file
415
internal/index/builder.go
Normal file
@@ -0,0 +1,415 @@
|
||||
package index
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/doc"
|
||||
"go/parser"
|
||||
"go/printer"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Build walks the Einherjar repository rooted at repoRoot, indexes every
|
||||
// sibling module (any immediate subdirectory containing a go.mod), and
|
||||
// returns an Index ready to be written to disk.
|
||||
//
|
||||
// The mcp module itself is skipped to avoid self-reference.
|
||||
func Build(repoRoot string) (*Index, error) {
|
||||
idx := &Index{
|
||||
Schema: SchemaVersion,
|
||||
Framework: "einherjar",
|
||||
BuiltAt: time.Now().UTC(),
|
||||
}
|
||||
entries, err := os.ReadDir(repoRoot)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read repo root: %w", err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
if strings.HasPrefix(name, ".") || name == "mcp" || name == "vendor" {
|
||||
continue
|
||||
}
|
||||
modDir := filepath.Join(repoRoot, name)
|
||||
if _, err := os.Stat(filepath.Join(modDir, "go.mod")); err != nil {
|
||||
continue
|
||||
}
|
||||
mod, err := buildModule(modDir, name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("module %s: %w", name, err)
|
||||
}
|
||||
idx.Modules = append(idx.Modules, *mod)
|
||||
}
|
||||
return idx, nil
|
||||
}
|
||||
|
||||
func buildModule(modDir, name string) (*Module, error) {
|
||||
m := &Module{
|
||||
Name: name,
|
||||
DependsOn: []string{},
|
||||
Compliance: Compliance{
|
||||
InterfaceAsserts: []InterfaceAssert{},
|
||||
Tests: []ComplianceTest{},
|
||||
},
|
||||
}
|
||||
|
||||
if data, err := os.ReadFile(filepath.Join(modDir, "go.mod")); err == nil {
|
||||
m.ImportPath = parseModulePath(data)
|
||||
m.GoVersion = parseGoVersion(data)
|
||||
m.DependsOn = parseDependsOn(data, name)
|
||||
}
|
||||
if data, err := os.ReadFile(filepath.Join(modDir, "README.md")); err == nil {
|
||||
m.Readme = string(data)
|
||||
m.Purpose = extractPurpose(string(data))
|
||||
m.Examples = extractExamples(name, string(data))
|
||||
}
|
||||
if data, err := os.ReadFile(filepath.Join(modDir, "CHANGELOG.md")); err == nil {
|
||||
m.Changelog = string(data)
|
||||
}
|
||||
m.Compliance = parseCompliance(name, modDir)
|
||||
|
||||
adrDir := filepath.Join(modDir, "docs", "adr")
|
||||
if adrs, err := os.ReadDir(adrDir); err == nil {
|
||||
for _, a := range adrs {
|
||||
if a.IsDir() || !strings.HasPrefix(a.Name(), "ADR-") || !strings.HasSuffix(a.Name(), ".md") {
|
||||
continue
|
||||
}
|
||||
body, err := os.ReadFile(filepath.Join(adrDir, a.Name()))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
id, title := parseADRHeader(a.Name(), body)
|
||||
m.ADRs = append(m.ADRs, ADR{Module: name, ID: id, Title: title, Body: string(body)})
|
||||
}
|
||||
}
|
||||
|
||||
if err := indexPackages(modDir, m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func indexPackages(modDir string, m *Module) error {
|
||||
return filepath.WalkDir(modDir, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if !d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
base := d.Name()
|
||||
if base != filepath.Base(modDir) && (strings.HasPrefix(base, ".") || base == "vendor" || base == "testdata" || base == "docs") {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
|
||||
fset := token.NewFileSet()
|
||||
pkgs, err := parser.ParseDir(fset, path, func(fi os.FileInfo) bool {
|
||||
return !strings.HasSuffix(fi.Name(), "_test.go")
|
||||
}, parser.ParseComments)
|
||||
if err != nil || len(pkgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
rel, _ := filepath.Rel(modDir, path)
|
||||
if rel == "." {
|
||||
rel = ""
|
||||
}
|
||||
for pkgName, pkg := range pkgs {
|
||||
if pkgName == "main" {
|
||||
continue
|
||||
}
|
||||
subName := pkgName
|
||||
if rel == "" {
|
||||
subName = ""
|
||||
}
|
||||
docPkg := doc.New(pkg, "./", doc.AllDecls)
|
||||
if rel == "" && m.Doc == "" && docPkg.Doc != "" {
|
||||
m.Doc = strings.TrimSpace(docPkg.Doc)
|
||||
}
|
||||
if rel != "" || docPkg.Doc != "" {
|
||||
m.SubPackages = append(m.SubPackages, SubPackage{
|
||||
Name: subName,
|
||||
ImportPath: joinImport(m.ImportPath, rel),
|
||||
Doc: strings.TrimSpace(docPkg.Doc),
|
||||
})
|
||||
}
|
||||
collectSymbols(m, subName, modDir, fset, docPkg)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func collectSymbols(m *Module, sub, modDir string, fset *token.FileSet, p *doc.Package) {
|
||||
for _, t := range p.Types {
|
||||
kind := "type"
|
||||
if isInterface(t.Decl) {
|
||||
kind = "interface"
|
||||
}
|
||||
m.Symbols = append(m.Symbols, newSymbol(m.Name, sub, kind, t.Name, t.Doc, t.Decl, fset, modDir))
|
||||
for _, f := range t.Funcs {
|
||||
m.Symbols = append(m.Symbols, newSymbol(m.Name, sub, "func", f.Name, f.Doc, f.Decl, fset, modDir))
|
||||
}
|
||||
for _, f := range t.Methods {
|
||||
m.Symbols = append(m.Symbols, newSymbol(m.Name, sub, "method", t.Name+"."+f.Name, f.Doc, f.Decl, fset, modDir))
|
||||
}
|
||||
}
|
||||
for _, f := range p.Funcs {
|
||||
m.Symbols = append(m.Symbols, newSymbol(m.Name, sub, "func", f.Name, f.Doc, f.Decl, fset, modDir))
|
||||
}
|
||||
for _, v := range p.Consts {
|
||||
for _, name := range v.Names {
|
||||
m.Symbols = append(m.Symbols, newSymbol(m.Name, sub, "const", name, v.Doc, v.Decl, fset, modDir))
|
||||
}
|
||||
}
|
||||
for _, v := range p.Vars {
|
||||
for _, name := range v.Names {
|
||||
m.Symbols = append(m.Symbols, newSymbol(m.Name, sub, "var", name, v.Doc, v.Decl, fset, modDir))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newSymbol(mod, sub, kind, name, docStr string, decl ast.Node, fset *token.FileSet, modDir string) Symbol {
|
||||
pos := fset.Position(decl.Pos())
|
||||
rel, _ := filepath.Rel(modDir, pos.Filename)
|
||||
return Symbol{
|
||||
Module: mod,
|
||||
SubPackage: sub,
|
||||
Kind: kind,
|
||||
Name: name,
|
||||
Signature: formatNode(fset, decl),
|
||||
Doc: strings.TrimSpace(docStr),
|
||||
File: rel,
|
||||
Line: pos.Line,
|
||||
}
|
||||
}
|
||||
|
||||
func formatNode(fset *token.FileSet, node ast.Node) string {
|
||||
var buf bytes.Buffer
|
||||
cfg := printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}
|
||||
if err := cfg.Fprint(&buf, fset, node); err != nil {
|
||||
return ""
|
||||
}
|
||||
s := buf.String()
|
||||
if i := strings.Index(s, "{"); i > 0 && (strings.HasPrefix(s, "func") || strings.HasPrefix(s, "type")) {
|
||||
return strings.TrimSpace(s[:i])
|
||||
}
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func isInterface(decl *ast.GenDecl) bool {
|
||||
if decl == nil {
|
||||
return false
|
||||
}
|
||||
for _, spec := range decl.Specs {
|
||||
ts, ok := spec.(*ast.TypeSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := ts.Type.(*ast.InterfaceType); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
modulePathRe = regexp.MustCompile(`(?m)^module\s+(\S+)`)
|
||||
goVersionRe = regexp.MustCompile(`(?m)^go\s+(\S+)`)
|
||||
adrNameRe = regexp.MustCompile(`^(ADR-\d+)-(.+)\.md$`)
|
||||
h1Re = regexp.MustCompile(`(?m)^#\s+(.+)$`)
|
||||
fenceRe = regexp.MustCompile("(?s)```([a-zA-Z0-9_+\\-]*)\\n(.*?)```")
|
||||
einherjarDepRe = regexp.MustCompile(`code\.nochebuena\.dev/einherjar/([a-zA-Z0-9_-]+)`)
|
||||
)
|
||||
|
||||
func parseModulePath(data []byte) string {
|
||||
if m := modulePathRe.FindSubmatch(data); m != nil {
|
||||
return string(m[1])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseGoVersion(data []byte) string {
|
||||
if m := goVersionRe.FindSubmatch(data); m != nil {
|
||||
return string(m[1])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseDependsOn extracts the set of einherjar modules referenced by go.mod's
|
||||
// require/replace lines. The module's own name is filtered out so a module
|
||||
// never lists itself as a dependency.
|
||||
func parseDependsOn(data []byte, self string) []string {
|
||||
seen := map[string]bool{}
|
||||
for _, m := range einherjarDepRe.FindAllSubmatch(data, -1) {
|
||||
name := string(m[1])
|
||||
if name == self {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
}
|
||||
out := make([]string, 0, len(seen))
|
||||
for k := range seen {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// parseCompliance parses compliance_test.go (when present) and returns its
|
||||
// interface assertions and test functions. Missing or unparseable files yield
|
||||
// an empty Compliance, not an error — the file is optional.
|
||||
func parseCompliance(modName, modDir string) Compliance {
|
||||
c := Compliance{
|
||||
InterfaceAsserts: []InterfaceAssert{},
|
||||
Tests: []ComplianceTest{},
|
||||
}
|
||||
path := filepath.Join(modDir, "compliance_test.go")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return c
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fset, path, data, parser.ParseComments)
|
||||
if err != nil {
|
||||
return c
|
||||
}
|
||||
rel, _ := filepath.Rel(modDir, path)
|
||||
|
||||
for _, decl := range file.Decls {
|
||||
switch d := decl.(type) {
|
||||
case *ast.GenDecl:
|
||||
if d.Tok != token.VAR {
|
||||
continue
|
||||
}
|
||||
for _, spec := range d.Specs {
|
||||
vs, ok := spec.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if len(vs.Names) != 1 || vs.Names[0].Name != "_" {
|
||||
continue
|
||||
}
|
||||
if vs.Type == nil || len(vs.Values) == 0 {
|
||||
continue
|
||||
}
|
||||
c.InterfaceAsserts = append(c.InterfaceAsserts, InterfaceAssert{
|
||||
Module: modName,
|
||||
Interface: formatNode(fset, vs.Type),
|
||||
Impl: formatNode(fset, vs.Values[0]),
|
||||
File: rel,
|
||||
Line: fset.Position(vs.Pos()).Line,
|
||||
})
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
if d.Recv != nil {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(d.Name.Name, "Test") {
|
||||
continue
|
||||
}
|
||||
testDoc := ""
|
||||
if d.Doc != nil {
|
||||
testDoc = strings.TrimSpace(d.Doc.Text())
|
||||
}
|
||||
c.Tests = append(c.Tests, ComplianceTest{
|
||||
Module: modName,
|
||||
Name: d.Name.Name,
|
||||
Doc: testDoc,
|
||||
File: rel,
|
||||
Line: fset.Position(d.Pos()).Line,
|
||||
})
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func parseADRHeader(filename string, body []byte) (id, title string) {
|
||||
if m := adrNameRe.FindStringSubmatch(filename); m != nil {
|
||||
id = m[1]
|
||||
title = strings.ReplaceAll(m[2], "-", " ")
|
||||
}
|
||||
if m := h1Re.FindSubmatch(body); m != nil {
|
||||
title = strings.TrimSpace(string(m[1]))
|
||||
}
|
||||
return id, title
|
||||
}
|
||||
|
||||
// extractPurpose returns the first non-empty, non-heading, non-badge paragraph
|
||||
// from the README — typically the blockquote tagline or opening sentence.
|
||||
func extractPurpose(readme string) string {
|
||||
for _, line := range strings.Split(readme, "\n") {
|
||||
t := strings.TrimSpace(line)
|
||||
if t == "" || strings.HasPrefix(t, "#") || strings.HasPrefix(t, "[!") || strings.HasPrefix(t, "[![") {
|
||||
continue
|
||||
}
|
||||
t = strings.TrimPrefix(t, "> ")
|
||||
t = strings.TrimPrefix(t, ">")
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
return t
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// extractExamples lifts fenced code blocks from a README, attaching them to
|
||||
// the most recent H2/H3 heading as the example title and the best-guess
|
||||
// sub-package (the heading lowercased, matched against known sub-packages
|
||||
// later — or left blank).
|
||||
func extractExamples(module, readme string) []Example {
|
||||
var out []Example
|
||||
lines := strings.Split(readme, "\n")
|
||||
currentHeading := ""
|
||||
for _, l := range lines {
|
||||
t := strings.TrimSpace(l)
|
||||
if strings.HasPrefix(t, "## ") || strings.HasPrefix(t, "### ") {
|
||||
currentHeading = strings.TrimSpace(strings.TrimLeft(t, "# "))
|
||||
}
|
||||
}
|
||||
_ = currentHeading // headings are walked again below to correlate blocks
|
||||
|
||||
matches := fenceRe.FindAllStringSubmatchIndex(readme, -1)
|
||||
for _, m := range matches {
|
||||
lang := readme[m[2]:m[3]]
|
||||
code := readme[m[4]:m[5]]
|
||||
title := nearestHeading(readme, m[0])
|
||||
out = append(out, Example{
|
||||
Module: module,
|
||||
Title: title,
|
||||
Code: strings.TrimSpace(code),
|
||||
Language: lang,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func nearestHeading(readme string, before int) string {
|
||||
prefix := readme[:before]
|
||||
lines := strings.Split(prefix, "\n")
|
||||
for i := len(lines) - 1; i >= 0; i-- {
|
||||
t := strings.TrimSpace(lines[i])
|
||||
if strings.HasPrefix(t, "## ") || strings.HasPrefix(t, "### ") {
|
||||
return strings.TrimSpace(strings.TrimLeft(t, "# "))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func joinImport(base, rel string) string {
|
||||
if base == "" {
|
||||
return ""
|
||||
}
|
||||
if rel == "" || rel == "." {
|
||||
return base
|
||||
}
|
||||
return base + "/" + filepath.ToSlash(rel)
|
||||
}
|
||||
35
internal/index/builtins.go
Normal file
35
internal/index/builtins.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package index
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
//go:embed builtins/README.md
|
||||
var builtinsReadme string
|
||||
|
||||
// BuildBuiltins returns the synthetic "wire" module that documents canonical
|
||||
// Einherjar application wiring conventions. The content is authored as
|
||||
// markdown in builtins/README.md and embedded at compile time.
|
||||
//
|
||||
// The returned module participates in list_modules, get_module, and
|
||||
// get_example exactly like a real Einherjar module — applications can ask
|
||||
// the MCP server for "wire" knowledge the same way they ask for "core" or
|
||||
// "web" knowledge.
|
||||
func BuildBuiltins() Module {
|
||||
m := Module{
|
||||
Name: "wire",
|
||||
ImportPath: "(application internal/wire)",
|
||||
Purpose: extractPurpose(builtinsReadme),
|
||||
Readme: builtinsReadme,
|
||||
DependsOn: []string{},
|
||||
SubPackages: []SubPackage{},
|
||||
Symbols: []Symbol{},
|
||||
ADRs: []ADR{},
|
||||
Compliance: Compliance{
|
||||
InterfaceAsserts: []InterfaceAssert{},
|
||||
Tests: []ComplianceTest{},
|
||||
},
|
||||
}
|
||||
m.Examples = extractExamples("wire", builtinsReadme)
|
||||
return m
|
||||
}
|
||||
338
internal/index/builtins/README.md
Normal file
338
internal/index/builtins/README.md
Normal file
@@ -0,0 +1,338 @@
|
||||
# Wiring Conventions
|
||||
|
||||
> Forging a service is mostly wiring. Do it the same way every time.
|
||||
|
||||
This is not an Einherjar *module* — it is the canonical *application* shape
|
||||
that uses Einherjar modules. Apps live in their own repository with an
|
||||
`internal/wire/` package that mirrors this template. The conventions here are
|
||||
distilled from a production service that has shipped on the predecessor
|
||||
micro-libs (`code.nochebuena.dev/go/*`) and have been re-mapped to the
|
||||
einherjar import paths.
|
||||
|
||||
## Project layout
|
||||
|
||||
```
|
||||
cmd/<app>/main.go one-line entrypoint that calls wire.Run()
|
||||
internal/wire/launcher.go Run() — builds infra and registers feature hooks
|
||||
internal/wire/<feature>.go one file per feature, hosts a with<Feature> hook
|
||||
internal/wire/middleware.go authz, skipPublicPaths, skipMethodPath helpers
|
||||
internal/wire/migrations.go withMigrations hook
|
||||
internal/wire/seed.go withSuperAdminSeed and other startup seeds
|
||||
internal/<feature>/dto/ request/response DTOs
|
||||
internal/<feature>/handler/ HTTP handlers
|
||||
internal/<feature>/repository/ data access
|
||||
internal/<feature>/service/ domain logic
|
||||
```
|
||||
|
||||
`cmd/<app>/main.go` must contain nothing but the call to `wire.Run()` and an
|
||||
`os.Exit(1)` on error. Everything else lives in `internal/wire/`.
|
||||
|
||||
## Run
|
||||
|
||||
The application entry point. The order below is load-bearing: configuration
|
||||
first, observability second, infrastructure third, cross-cutting helpers
|
||||
fourth, then the launcher with every component appended, then feature hooks,
|
||||
then `lc.Run()`.
|
||||
|
||||
```go
|
||||
package wire
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
authjwt "code.nochebuena.dev/einherjar/auth-jwt"
|
||||
"code.nochebuena.dev/einherjar/auth/authmw"
|
||||
"code.nochebuena.dev/einherjar/auth/rbac"
|
||||
"code.nochebuena.dev/einherjar/cache-valkey"
|
||||
"code.nochebuena.dev/einherjar/core/launcher"
|
||||
"code.nochebuena.dev/einherjar/core/logz"
|
||||
"code.nochebuena.dev/einherjar/core/valid"
|
||||
"code.nochebuena.dev/einherjar/db-postgres"
|
||||
"code.nochebuena.dev/einherjar/storage-minio"
|
||||
"code.nochebuena.dev/einherjar/web/mw"
|
||||
"code.nochebuena.dev/einherjar/web/server"
|
||||
"code.nochebuena.dev/einherjar/worker"
|
||||
|
||||
"myapp/internal/config"
|
||||
)
|
||||
|
||||
func Run() error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger := logz.New(logz.Config{
|
||||
JSON: !strings.EqualFold(cfg.AppEnv, "local"),
|
||||
StaticArgs: []any{"service", "myapp", "env", cfg.AppEnv},
|
||||
})
|
||||
|
||||
signer := authjwt.NewHMACSigner([]byte(cfg.JWT.Secret))
|
||||
|
||||
publicPaths := []string{
|
||||
"/health",
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/refresh",
|
||||
}
|
||||
|
||||
db := postgres.New(logger, cfg.PG)
|
||||
cache := valkey.New(logger, cfg.VK)
|
||||
pool := worker.New(logger, cfg.Worker)
|
||||
mc := minio.New(logger, cfg.MinIO)
|
||||
srv := server.New(logger, cfg.Server,
|
||||
server.WithMiddleware(
|
||||
mw.RequestID(uuid.NewString),
|
||||
mw.Recover(logger),
|
||||
mw.CORS(cfg.CORSOrigins),
|
||||
mw.RequestLogger(logger),
|
||||
authjwt.AuthMiddleware(logger, signer, publicPaths),
|
||||
authmw.EnrichmentMiddleware(logger, &claimsEnricher{}),
|
||||
),
|
||||
)
|
||||
|
||||
v := valid.New(valid.WithMessageProvider(valid.SpanishMessages))
|
||||
provider := rbac.NewClaimsPermissionProvider("masks", claimsFromCtx)
|
||||
|
||||
lc := launcher.New(logger)
|
||||
lc.Append(db, cache, pool, mc, srv)
|
||||
|
||||
withMigrations(lc, logger, cfg)
|
||||
withSuperAdminSeed(lc, db, logger, cfg)
|
||||
|
||||
withHealth(lc, srv, logger, db, cache, mc)
|
||||
withUsers(lc, srv, db, logger, provider, v)
|
||||
// … one withFeature(...) call per feature in your domain.
|
||||
|
||||
return lc.Run()
|
||||
}
|
||||
```
|
||||
|
||||
## Feature hook
|
||||
|
||||
One file per feature in `internal/wire/`. The function signature is fixed:
|
||||
`launcher.Launcher` first, `server.Server` second when registering routes,
|
||||
deps last. The body is *one* call to `lc.BeforeStart`. Everything else —
|
||||
repository construction, service construction, handler construction, route
|
||||
registration — lives inside the closure.
|
||||
|
||||
```go
|
||||
package wire
|
||||
|
||||
import (
|
||||
"code.nochebuena.dev/einherjar/contracts/security"
|
||||
"code.nochebuena.dev/einherjar/core/launcher"
|
||||
"code.nochebuena.dev/einherjar/core/logz"
|
||||
"code.nochebuena.dev/einherjar/core/valid"
|
||||
"code.nochebuena.dev/einherjar/db-postgres"
|
||||
"code.nochebuena.dev/einherjar/web/server"
|
||||
|
||||
"myapp/internal/domains"
|
||||
userhandler "myapp/internal/user/handler"
|
||||
userrepo "myapp/internal/user/repository"
|
||||
usersvc "myapp/internal/user/service"
|
||||
)
|
||||
|
||||
func withUsers(
|
||||
lc launcher.Launcher,
|
||||
srv server.Server,
|
||||
db postgres.Component,
|
||||
logger logz.Logger,
|
||||
provider security.PermissionProvider,
|
||||
v valid.Validator,
|
||||
) {
|
||||
lc.BeforeStart(func() error {
|
||||
repo := userrepo.New(db)
|
||||
uow := postgres.NewUnitOfWork(logger, db)
|
||||
svc := usersvc.New(repo, uow)
|
||||
h := userhandler.New(svc, v)
|
||||
|
||||
// Literal-segment routes register BEFORE parametrised siblings.
|
||||
// chi matches the first registered route that fits; if /users/{id}
|
||||
// came first, "me" would bind to {id} and /users/me/password would
|
||||
// never be reached.
|
||||
srv.Put("/api/v1/users/me/password", h.ChangeOwnPassword)
|
||||
|
||||
srv.With(authz(provider, domains.ResourceUsers, domains.GrantReadUser)).
|
||||
Get("/api/v1/users", h.ListUsers)
|
||||
srv.With(authz(provider, domains.ResourceUsers, domains.GrantCreateUser)).
|
||||
Post("/api/v1/users", h.CreateUser)
|
||||
srv.With(authz(provider, domains.ResourceUsers, domains.GrantUpdateUser)).
|
||||
Put("/api/v1/users/{user_id}", h.UpdateUser)
|
||||
srv.With(authz(provider, domains.ResourceUsers, domains.GrantDeleteUser)).
|
||||
Delete("/api/v1/users/{user_id}", h.DeleteUser)
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Route ordering
|
||||
|
||||
chi matches paths in registration order. Always register literal-segment
|
||||
routes before parametrised-segment routes that share the same prefix.
|
||||
|
||||
✅ Correct:
|
||||
|
||||
```go
|
||||
srv.Put("/api/v1/users/me/password", h.ChangeOwnPassword)
|
||||
srv.Put("/api/v1/users/{user_id}", h.UpdateUser)
|
||||
```
|
||||
|
||||
❌ Wrong — chi binds `me` to `{user_id}` and the literal route is unreachable:
|
||||
|
||||
```go
|
||||
srv.Put("/api/v1/users/{user_id}", h.UpdateUser)
|
||||
srv.Put("/api/v1/users/me/password", h.ChangeOwnPassword)
|
||||
```
|
||||
|
||||
## Authorization
|
||||
|
||||
Every protected route registers with `.With(authz(provider, resource, grant))`:
|
||||
|
||||
```go
|
||||
srv.With(authz(provider, domains.ResourceUsers, domains.GrantReadUser)).
|
||||
Get("/api/v1/users", h.ListUsers)
|
||||
```
|
||||
|
||||
Resource constants and grant bits live in `internal/domains/`. Routes that
|
||||
the caller owns (`/me/...`) intentionally skip authz — they are reachable to
|
||||
any authenticated user.
|
||||
|
||||
## Middleware helpers
|
||||
|
||||
These belong in `internal/wire/middleware.go` and are used across every
|
||||
feature hook.
|
||||
|
||||
```go
|
||||
// authz returns a per-route authorization middleware that checks one bit.
|
||||
func authz(p security.PermissionProvider, resource string, bit int) func(http.Handler) http.Handler {
|
||||
return authmw.AuthzMiddleware(nil, p, resource, security.Permission(bit))
|
||||
}
|
||||
|
||||
// skipPublicPaths wraps mw so it is bypassed for any path that matches publicPaths.
|
||||
// Use this for middleware that must not run on unauthenticated endpoints
|
||||
// (e.g. EnrichmentMiddleware).
|
||||
func skipPublicPaths(publicPaths []string, mw func(http.Handler) http.Handler) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
inner := mw(next)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
for _, p := range publicPaths {
|
||||
if matched, _ := path.Match(p, r.URL.Path); matched {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
inner.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// skipMethodPath bypasses mw only when BOTH method and path match. Use this
|
||||
// to expose ONE method on an otherwise-authenticated path (e.g. GET
|
||||
// /api/v1/config public while PUT is not). Adding such a path to
|
||||
// publicPaths would silently strip identity from context on the protected
|
||||
// methods, breaking authz().
|
||||
func skipMethodPath(method, pathPattern string, mw func(http.Handler) http.Handler) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
inner := mw(next)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == method {
|
||||
if matched, _ := path.Match(pathPattern, r.URL.Path); matched {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
inner.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Adapters at the wire boundary
|
||||
|
||||
When a framework type does not match a service-layer port, write a small
|
||||
typed adapter in `internal/wire/`. Always compile-time assert with
|
||||
`var _ TargetIface = (*adapter)(nil)`.
|
||||
|
||||
The framework intentionally exposes only `Signer.Sign(claims) (string, error)`
|
||||
— **the framework gives you a signing primitive; the access/refresh strategy,
|
||||
claim layout, and response shape are application concerns.** A "helper" that
|
||||
returned a fixed `{access, refresh, type, expiresIn}` struct would silently
|
||||
decide for every app whether refresh tokens exist, what fields to expose,
|
||||
and what casing to use. Those are wire-format choices the app owns.
|
||||
|
||||
```go
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
authjwt "code.nochebuena.dev/einherjar/auth-jwt"
|
||||
)
|
||||
|
||||
type tokenSignerAdapter struct {
|
||||
signer authjwt.Signer
|
||||
cfg authjwt.TokenConfig
|
||||
}
|
||||
|
||||
var _ authsvc.TokenSigner = (*tokenSignerAdapter)(nil)
|
||||
|
||||
func (a *tokenSignerAdapter) IssueTokenPair(subject string, custom map[string]any) (authdto.TokenPairResponse, error) {
|
||||
now := time.Now()
|
||||
|
||||
access := jwt.MapClaims{
|
||||
"sub": subject,
|
||||
"iss": a.cfg.Issuer,
|
||||
"iat": now.Unix(),
|
||||
"exp": now.Add(a.cfg.AccessTTL).Unix(),
|
||||
}
|
||||
for k, v := range custom {
|
||||
access[k] = v
|
||||
}
|
||||
accessToken, err := a.signer.Sign(access)
|
||||
if err != nil {
|
||||
return authdto.TokenPairResponse{}, err
|
||||
}
|
||||
|
||||
refreshToken, err := a.signer.Sign(jwt.MapClaims{
|
||||
"sub": subject,
|
||||
"jti": uuid.NewString(),
|
||||
"iat": now.Unix(),
|
||||
"exp": now.Add(a.cfg.RefreshTTL).Unix(),
|
||||
})
|
||||
if err != nil {
|
||||
return authdto.TokenPairResponse{}, err
|
||||
}
|
||||
|
||||
return authdto.TokenPairResponse{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: int(a.cfg.AccessTTL.Seconds()),
|
||||
}, nil
|
||||
}
|
||||
```
|
||||
|
||||
## Migrations and seeds
|
||||
|
||||
Migrations and seeds register as `BeforeStart` hooks too. They run after all
|
||||
components have initialised but before any of them have started, so the
|
||||
database is reachable and the server is not yet accepting traffic.
|
||||
|
||||
```go
|
||||
func withMigrations(lc launcher.Launcher, logger logz.Logger, cfg config.Config) {
|
||||
lc.BeforeStart(func() error {
|
||||
if err := migrations.RunMigrations(context.Background(), logger, cfg); err != nil {
|
||||
logger.Error("migrations: failed to apply", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Seeds must be **idempotent**: count first, only mutate when needed, log the
|
||||
skip when nothing was done.
|
||||
164
internal/index/index.go
Normal file
164
internal/index/index.go
Normal file
@@ -0,0 +1,164 @@
|
||||
// Package index defines the on-disk schema of the Einherjar framework index
|
||||
// and provides a loader for the embedded JSON blob.
|
||||
//
|
||||
// The index is built once at deploy time by cmd/indexer and consumed by every
|
||||
// MCP tool. Keeping it small, denormalised, and JSON-shaped means tools can
|
||||
// be implemented as straightforward in-memory filters.
|
||||
package index
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SchemaVersion identifies the on-disk index format. Bump when fields change
|
||||
// in a way that breaks older consumers.
|
||||
const SchemaVersion = "einherjar.mcp/index/v1"
|
||||
|
||||
// Index is the root of the embedded framework knowledge.
|
||||
type Index struct {
|
||||
Schema string `json:"schema"`
|
||||
Framework string `json:"framework"`
|
||||
BuiltAt time.Time `json:"builtAt"`
|
||||
Modules []Module `json:"modules"`
|
||||
}
|
||||
|
||||
// Module describes one Einherjar module (e.g. core, web, auth-jwt).
|
||||
type Module struct {
|
||||
Name string `json:"name"`
|
||||
ImportPath string `json:"importPath"`
|
||||
Purpose string `json:"purpose"`
|
||||
Doc string `json:"doc,omitempty"`
|
||||
GoVersion string `json:"goVersion"`
|
||||
DependsOn []string `json:"dependsOn"`
|
||||
SubPackages []SubPackage `json:"subPackages"`
|
||||
Symbols []Symbol `json:"symbols"`
|
||||
ADRs []ADR `json:"adrs"`
|
||||
Examples []Example `json:"examples"`
|
||||
Compliance Compliance `json:"compliance"`
|
||||
Readme string `json:"readme,omitempty"`
|
||||
Changelog string `json:"changelog,omitempty"`
|
||||
}
|
||||
|
||||
// Compliance captures a module's compliance_test.go contents: compile-time
|
||||
// interface assertions and the names of structural tests. It exists so an AI
|
||||
// assistant can know about machine-checked conventions before it writes code
|
||||
// that would violate them.
|
||||
type Compliance struct {
|
||||
InterfaceAsserts []InterfaceAssert `json:"interfaceAsserts"`
|
||||
Tests []ComplianceTest `json:"tests"`
|
||||
}
|
||||
|
||||
// InterfaceAssert mirrors one `var _ Iface = impl` line in compliance_test.go.
|
||||
type InterfaceAssert struct {
|
||||
Module string `json:"module"`
|
||||
Interface string `json:"interface"`
|
||||
Impl string `json:"impl"`
|
||||
File string `json:"file"`
|
||||
Line int `json:"line"`
|
||||
}
|
||||
|
||||
// ComplianceTest mirrors one Test* function in compliance_test.go.
|
||||
type ComplianceTest struct {
|
||||
Module string `json:"module"`
|
||||
Name string `json:"name"`
|
||||
Doc string `json:"doc"`
|
||||
File string `json:"file"`
|
||||
Line int `json:"line"`
|
||||
}
|
||||
|
||||
// SubPackage is one importable sub-package of a module.
|
||||
type SubPackage struct {
|
||||
Name string `json:"name"`
|
||||
ImportPath string `json:"importPath"`
|
||||
Doc string `json:"doc"`
|
||||
}
|
||||
|
||||
// Symbol is one exported declaration (type, func, interface, const, var).
|
||||
type Symbol struct {
|
||||
Module string `json:"module"`
|
||||
SubPackage string `json:"subPackage"`
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
Signature string `json:"signature"`
|
||||
Doc string `json:"doc"`
|
||||
File string `json:"file"`
|
||||
Line int `json:"line"`
|
||||
}
|
||||
|
||||
// ADR is one architectural decision record.
|
||||
type ADR struct {
|
||||
Module string `json:"module"`
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// Example is a fenced code block lifted from a module README.
|
||||
type Example struct {
|
||||
Module string `json:"module"`
|
||||
SubPackage string `json:"subPackage"`
|
||||
Title string `json:"title"`
|
||||
Code string `json:"code"`
|
||||
Language string `json:"language"`
|
||||
}
|
||||
|
||||
// Load parses the embedded JSON blob into an Index. It validates the schema
|
||||
// version and returns an empty (but non-nil) Index when the blob is the
|
||||
// placeholder shipped before the indexer has been run.
|
||||
func Load(raw []byte) (*Index, error) {
|
||||
if len(raw) == 0 {
|
||||
return &Index{Schema: SchemaVersion, Framework: "einherjar"}, nil
|
||||
}
|
||||
idx := &Index{}
|
||||
if err := json.Unmarshal(raw, idx); err != nil {
|
||||
return nil, fmt.Errorf("index: parse: %w", err)
|
||||
}
|
||||
if idx.Schema != "" && idx.Schema != SchemaVersion {
|
||||
return nil, fmt.Errorf("index: schema mismatch: got %q want %q", idx.Schema, SchemaVersion)
|
||||
}
|
||||
return idx, nil
|
||||
}
|
||||
|
||||
// FindModule returns the module with the given name, or nil if absent.
|
||||
func (i *Index) FindModule(name string) *Module {
|
||||
for k := range i.Modules {
|
||||
if i.Modules[k].Name == name {
|
||||
return &i.Modules[k]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SearchSymbols returns up to limit symbols whose name or doc contains q
|
||||
// (case-insensitive). Module name and sub-package are also searched.
|
||||
func (i *Index) SearchSymbols(q string, limit int) []Symbol {
|
||||
if limit <= 0 {
|
||||
limit = 25
|
||||
}
|
||||
needle := strings.ToLower(q)
|
||||
out := make([]Symbol, 0, limit)
|
||||
for _, m := range i.Modules {
|
||||
for _, s := range m.Symbols {
|
||||
if matches(s, needle) {
|
||||
out = append(out, s)
|
||||
if len(out) >= limit {
|
||||
return out
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func matches(s Symbol, needle string) bool {
|
||||
if needle == "" {
|
||||
return true
|
||||
}
|
||||
return strings.Contains(strings.ToLower(s.Name), needle) ||
|
||||
strings.Contains(strings.ToLower(s.Doc), needle) ||
|
||||
strings.Contains(strings.ToLower(s.SubPackage), needle) ||
|
||||
strings.Contains(strings.ToLower(s.Module), needle)
|
||||
}
|
||||
286
internal/rules/rules.go
Normal file
286
internal/rules/rules.go
Normal file
@@ -0,0 +1,286 @@
|
||||
// Package rules defines the lightweight, pattern-based conventions enforced
|
||||
// by the validate_snippet MCP tool.
|
||||
//
|
||||
// These are not a substitute for "go vet" or running the user's tests. They
|
||||
// catch wiring mistakes that an AI assistant frequently makes when first
|
||||
// adopting Einherjar: forgetting to call Run(), constructing a Launcher
|
||||
// without registering components, reading EINHERJAR_* env vars directly
|
||||
// instead of letting the framework load them, and so on.
|
||||
package rules
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Severity describes how seriously a finding should be treated.
|
||||
type Severity string
|
||||
|
||||
const (
|
||||
SeverityError Severity = "error"
|
||||
SeverityWarning Severity = "warning"
|
||||
SeverityInfo Severity = "info"
|
||||
)
|
||||
|
||||
// Finding is one rule hit against a snippet.
|
||||
type Finding struct {
|
||||
RuleID string `json:"ruleId"`
|
||||
Severity Severity `json:"severity"`
|
||||
Module string `json:"module,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
Line int `json:"line,omitempty"`
|
||||
}
|
||||
|
||||
// Rule is a single named convention check.
|
||||
type Rule struct {
|
||||
ID string
|
||||
Severity Severity
|
||||
Module string
|
||||
Check func(ctx *Context) []Finding
|
||||
}
|
||||
|
||||
// Context is the parsed view of a snippet provided to every rule.
|
||||
type Context struct {
|
||||
Fset *token.FileSet
|
||||
File *ast.File
|
||||
Imports map[string]string // path → local name (e.g. "code.nochebuena.dev/einherjar/core/launcher" → "launcher")
|
||||
Calls []CallSite // every function call in the file
|
||||
}
|
||||
|
||||
// CallSite is a recorded function call. Func is the textual form
|
||||
// ("launcher.New", "lc.Append", "lc.Run").
|
||||
type CallSite struct {
|
||||
Func string
|
||||
Line int
|
||||
}
|
||||
|
||||
// Run parses the source and applies every rule, returning all findings in
|
||||
// order. If the source cannot be parsed even after wrapping in a synthetic
|
||||
// package, parse errors are returned as findings with rule id "parse".
|
||||
func Run(src string) []Finding {
|
||||
fset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fset, "snippet.go", src, parser.AllErrors|parser.ParseComments)
|
||||
if err != nil {
|
||||
wrapped := "package _snippet\n\nfunc _main() {\n" + src + "\n}\n"
|
||||
fset = token.NewFileSet()
|
||||
file, err = parser.ParseFile(fset, "snippet.go", wrapped, parser.AllErrors|parser.ParseComments)
|
||||
if err != nil {
|
||||
return []Finding{{
|
||||
RuleID: "parse",
|
||||
Severity: SeverityError,
|
||||
Message: "could not parse snippet: " + err.Error(),
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
ctx := &Context{Fset: fset, File: file, Imports: map[string]string{}}
|
||||
for _, imp := range file.Imports {
|
||||
path := strings.Trim(imp.Path.Value, `"`)
|
||||
name := guessImportName(path)
|
||||
if imp.Name != nil && imp.Name.Name != "" && imp.Name.Name != "_" {
|
||||
name = imp.Name.Name
|
||||
}
|
||||
ctx.Imports[path] = name
|
||||
}
|
||||
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
name := exprName(call.Fun)
|
||||
if name == "" {
|
||||
return true
|
||||
}
|
||||
ctx.Calls = append(ctx.Calls, CallSite{Func: name, Line: fset.Position(call.Pos()).Line})
|
||||
return true
|
||||
})
|
||||
|
||||
var findings []Finding
|
||||
for _, r := range registered {
|
||||
for _, f := range r.Check(ctx) {
|
||||
f.RuleID = r.ID
|
||||
if f.Severity == "" {
|
||||
f.Severity = r.Severity
|
||||
}
|
||||
if f.Module == "" {
|
||||
f.Module = r.Module
|
||||
}
|
||||
findings = append(findings, f)
|
||||
}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
|
||||
func guessImportName(path string) string {
|
||||
i := strings.LastIndex(path, "/")
|
||||
if i < 0 {
|
||||
return path
|
||||
}
|
||||
return path[i+1:]
|
||||
}
|
||||
|
||||
func exprName(e ast.Expr) string {
|
||||
switch v := e.(type) {
|
||||
case *ast.Ident:
|
||||
return v.Name
|
||||
case *ast.SelectorExpr:
|
||||
return exprName(v.X) + "." + v.Sel.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Importing reports whether the snippet imports a path with the given suffix
|
||||
// (e.g. "core/launcher" matches "code.nochebuena.dev/einherjar/core/launcher").
|
||||
func (c *Context) Importing(suffix string) bool {
|
||||
for path := range c.Imports {
|
||||
if strings.HasSuffix(path, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Calls reports whether any call site has a textual form ending in suffix.
|
||||
// For example, suffix ".Run" matches "lc.Run" and "launcher.Run" alike.
|
||||
func (c *Context) Called(suffix string) bool {
|
||||
for _, cs := range c.Calls {
|
||||
if strings.HasSuffix(cs.Func, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// registered is the static rule catalog. Add new conventions here.
|
||||
var registered = []Rule{
|
||||
{
|
||||
ID: "launcher.missing-run",
|
||||
Severity: SeverityError,
|
||||
Module: "core",
|
||||
Check: func(c *Context) []Finding {
|
||||
if !c.Importing("einherjar/core/launcher") {
|
||||
return nil
|
||||
}
|
||||
if !c.Called("launcher.New") && !c.Called(".New") {
|
||||
return nil
|
||||
}
|
||||
if c.Called(".Run") {
|
||||
return nil
|
||||
}
|
||||
return []Finding{{
|
||||
Message: "core/launcher constructed but Run() never called — application will never start",
|
||||
Hint: "After lc := launcher.New(logger); lc.Append(...); call if err := lc.Run(); err != nil { ... }",
|
||||
}}
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "launcher.no-components",
|
||||
Severity: SeverityWarning,
|
||||
Module: "core",
|
||||
Check: func(c *Context) []Finding {
|
||||
if !c.Importing("einherjar/core/launcher") {
|
||||
return nil
|
||||
}
|
||||
if c.Called("launcher.New") && !c.Called(".Append") {
|
||||
return []Finding{{
|
||||
Message: "Launcher created but no components appended — Run() will start an empty application",
|
||||
Hint: "Use lc.Append(db, cache, server) before lc.Run() to register lifecycle components",
|
||||
}}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "logz.direct-env-read",
|
||||
Severity: SeverityWarning,
|
||||
Module: "core",
|
||||
Check: func(c *Context) []Finding {
|
||||
if !c.Importing("einherjar/core/logz") {
|
||||
return nil
|
||||
}
|
||||
var hits []Finding
|
||||
ast.Inspect(c.File, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if exprName(call.Fun) != "os.Getenv" || len(call.Args) == 0 {
|
||||
return true
|
||||
}
|
||||
lit, ok := call.Args[0].(*ast.BasicLit)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(strings.Trim(lit.Value, `"`), "EINHERJAR_LOG_") {
|
||||
hits = append(hits, Finding{
|
||||
Message: fmt.Sprintf("reading %s directly via os.Getenv bypasses logz configuration", strings.Trim(lit.Value, `"`)),
|
||||
Hint: "logz.New reads EINHERJAR_LOG_* automatically; pass logz.Config and let the framework load it",
|
||||
Line: c.Fset.Position(call.Pos()).Line,
|
||||
})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return hits
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "launcher.run-error-discarded",
|
||||
Severity: SeverityWarning,
|
||||
Module: "core",
|
||||
Check: func(c *Context) []Finding {
|
||||
if !c.Importing("einherjar/core/launcher") || !c.Called(".Run") {
|
||||
return nil
|
||||
}
|
||||
discarded := false
|
||||
ast.Inspect(c.File, func(n ast.Node) bool {
|
||||
expr, ok := n.(*ast.ExprStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
call, ok := expr.X.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if strings.HasSuffix(exprName(call.Fun), ".Run") {
|
||||
discarded = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
if !discarded {
|
||||
return nil
|
||||
}
|
||||
return []Finding{{
|
||||
Message: "Launcher.Run() return value discarded — startup failures will go unnoticed",
|
||||
Hint: "Capture the error: if err := lc.Run(); err != nil { logger.Error(...); os.Exit(1) }",
|
||||
}}
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "web.server-not-appended",
|
||||
Severity: SeverityWarning,
|
||||
Module: "web",
|
||||
Check: func(c *Context) []Finding {
|
||||
if !c.Importing("einherjar/web/server") || !c.Importing("einherjar/core/launcher") {
|
||||
return nil
|
||||
}
|
||||
if !c.Called(".Append") {
|
||||
return nil
|
||||
}
|
||||
// Heuristic: warn if server.New is constructed but not appended via .Append.
|
||||
// We can't statically prove the argument was the server, so this is informational.
|
||||
if c.Called("server.New") {
|
||||
return []Finding{{
|
||||
Severity: SeverityInfo,
|
||||
Message: "web/server is constructed — ensure it is passed to launcher.Append() so its lifecycle is managed",
|
||||
Hint: "lc.Append(srv) lets the launcher start and gracefully stop the HTTP server",
|
||||
}}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
233
internal/rules/wire_rules.go
Normal file
233
internal/rules/wire_rules.go
Normal file
@@ -0,0 +1,233 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registered = append(registered,
|
||||
Rule{
|
||||
ID: "wire.hook-bad-signature",
|
||||
Severity: SeverityWarning,
|
||||
Module: "wire",
|
||||
Check: checkHookSignature,
|
||||
},
|
||||
Rule{
|
||||
ID: "wire.hook-outside-beforestart",
|
||||
Severity: SeverityWarning,
|
||||
Module: "wire",
|
||||
Check: checkHookBodyShape,
|
||||
},
|
||||
Rule{
|
||||
ID: "wire.route-specific-after-param",
|
||||
Severity: SeverityWarning,
|
||||
Module: "web",
|
||||
Check: checkRouteOrdering,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// isHookName reports whether name matches the with<Feature> convention.
|
||||
// A hook is "with" + capital letter + anything, so "with" and "withers"
|
||||
// don't qualify but "withUsers", "withAuth", "withSuperAdminSeed" do.
|
||||
func isHookName(name string) bool {
|
||||
if len(name) < 5 || !strings.HasPrefix(name, "with") {
|
||||
return false
|
||||
}
|
||||
c := name[4]
|
||||
return c >= 'A' && c <= 'Z'
|
||||
}
|
||||
|
||||
func checkHookSignature(c *Context) []Finding {
|
||||
var findings []Finding
|
||||
for _, decl := range c.File.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if !ok || fn.Recv != nil || !isHookName(fn.Name.Name) {
|
||||
continue
|
||||
}
|
||||
params := fn.Type.Params
|
||||
if params == nil || len(params.List) == 0 {
|
||||
findings = append(findings, Finding{
|
||||
Message: fmt.Sprintf("hook %s has no parameters; expected first param launcher.Launcher", fn.Name.Name),
|
||||
Hint: "func with<Feature>(lc launcher.Launcher, srv server.Server, deps...)",
|
||||
Line: c.Fset.Position(fn.Pos()).Line,
|
||||
})
|
||||
continue
|
||||
}
|
||||
first := exprName(params.List[0].Type)
|
||||
if !strings.Contains(first, "Launcher") {
|
||||
findings = append(findings, Finding{
|
||||
Message: fmt.Sprintf("hook %s first param is %q; expected launcher.Launcher", fn.Name.Name, first),
|
||||
Hint: "Always pass the launcher as the first argument so the hook can register BeforeStart.",
|
||||
Line: c.Fset.Position(fn.Pos()).Line,
|
||||
})
|
||||
}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
|
||||
func checkHookBodyShape(c *Context) []Finding {
|
||||
var findings []Finding
|
||||
for _, decl := range c.File.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if !ok || fn.Recv != nil || fn.Body == nil || !isHookName(fn.Name.Name) {
|
||||
continue
|
||||
}
|
||||
for _, stmt := range fn.Body.List {
|
||||
if !suspiciousTopLevelStmt(stmt) {
|
||||
continue
|
||||
}
|
||||
findings = append(findings, Finding{
|
||||
Message: fmt.Sprintf("hook %s performs wiring outside lc.BeforeStart", fn.Name.Name),
|
||||
Hint: "Move repo/service/handler construction and route registration inside lc.BeforeStart(func() error { ... return nil }).",
|
||||
Line: c.Fset.Position(stmt.Pos()).Line,
|
||||
})
|
||||
}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
|
||||
// suspiciousTopLevelStmt is true for top-level statements inside a hook that
|
||||
// look like wiring work (route registration or component construction) but
|
||||
// are not the canonical lc.BeforeStart or lc.Append calls.
|
||||
func suspiciousTopLevelStmt(stmt ast.Stmt) bool {
|
||||
if expr, ok := stmt.(*ast.ExprStmt); ok {
|
||||
if call, ok := expr.X.(*ast.CallExpr); ok {
|
||||
name := exprName(call.Fun)
|
||||
if strings.HasSuffix(name, ".BeforeStart") ||
|
||||
strings.HasSuffix(name, ".Append") ||
|
||||
strings.HasSuffix(name, ".Run") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
suspicious := false
|
||||
ast.Inspect(stmt, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
name := exprName(call.Fun)
|
||||
switch {
|
||||
case strings.HasSuffix(name, ".Get"),
|
||||
strings.HasSuffix(name, ".Post"),
|
||||
strings.HasSuffix(name, ".Put"),
|
||||
strings.HasSuffix(name, ".Patch"),
|
||||
strings.HasSuffix(name, ".Delete"),
|
||||
strings.HasSuffix(name, ".New"):
|
||||
suspicious = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return suspicious
|
||||
}
|
||||
|
||||
type routeReg struct {
|
||||
method string
|
||||
path string
|
||||
pos token.Pos
|
||||
}
|
||||
|
||||
func collectRoutes(file *ast.File) []routeReg {
|
||||
var routes []routeReg
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
switch sel.Sel.Name {
|
||||
case "Get", "Post", "Put", "Patch", "Delete":
|
||||
default:
|
||||
return true
|
||||
}
|
||||
if len(call.Args) < 1 {
|
||||
return true
|
||||
}
|
||||
lit, ok := call.Args[0].(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
routes = append(routes, routeReg{
|
||||
method: sel.Sel.Name,
|
||||
path: strings.Trim(lit.Value, `"`),
|
||||
pos: call.Pos(),
|
||||
})
|
||||
return true
|
||||
})
|
||||
return routes
|
||||
}
|
||||
|
||||
func checkRouteOrdering(c *Context) []Finding {
|
||||
routes := collectRoutes(c.File)
|
||||
var findings []Finding
|
||||
for i := 0; i < len(routes); i++ {
|
||||
for j := i + 1; j < len(routes); j++ {
|
||||
if routes[i].method != routes[j].method {
|
||||
continue
|
||||
}
|
||||
if !routesConflict(routes[i].path, routes[j].path) {
|
||||
continue
|
||||
}
|
||||
findings = append(findings, Finding{
|
||||
Message: fmt.Sprintf("%s %s registered before %s %s — chi will bind %q to a path parameter and the literal route becomes unreachable",
|
||||
routes[i].method, routes[i].path,
|
||||
routes[j].method, routes[j].path,
|
||||
conflictingSegment(routes[i].path, routes[j].path),
|
||||
),
|
||||
Hint: "Register literal-segment routes before parametrised siblings that share the same prefix.",
|
||||
Line: c.Fset.Position(routes[i].pos).Line,
|
||||
})
|
||||
}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
|
||||
// routesConflict reports whether `param` is a parametrised route that would
|
||||
// shadow `literal` (a route differing only in one segment being a literal
|
||||
// where param has {placeholder}).
|
||||
func routesConflict(param, literal string) bool {
|
||||
p := strings.Split(strings.Trim(param, "/"), "/")
|
||||
l := strings.Split(strings.Trim(literal, "/"), "/")
|
||||
if len(p) != len(l) {
|
||||
return false
|
||||
}
|
||||
hasParam := false
|
||||
for i := range p {
|
||||
pIsParam := isParamSeg(p[i])
|
||||
lIsParam := isParamSeg(l[i])
|
||||
if pIsParam {
|
||||
if lIsParam {
|
||||
return false
|
||||
}
|
||||
hasParam = true
|
||||
continue
|
||||
}
|
||||
if p[i] != l[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return hasParam
|
||||
}
|
||||
|
||||
func isParamSeg(s string) bool {
|
||||
return strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")
|
||||
}
|
||||
|
||||
func conflictingSegment(param, literal string) string {
|
||||
p := strings.Split(strings.Trim(param, "/"), "/")
|
||||
l := strings.Split(strings.Trim(literal, "/"), "/")
|
||||
for i := range p {
|
||||
if isParamSeg(p[i]) && !isParamSeg(l[i]) {
|
||||
return l[i]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
40
internal/tools/get_adr.go
Normal file
40
internal/tools/get_adr.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type getADRInput struct {
|
||||
Module string `json:"module" jsonschema:"the module name owning the ADR, e.g. core"`
|
||||
ID string `json:"id" jsonschema:"the ADR identifier, e.g. ADR-001"`
|
||||
}
|
||||
|
||||
type getADROutput struct {
|
||||
Module string `json:"module"`
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
func registerGetADR(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "get_adr",
|
||||
Description: "Fetch the full markdown body of one architectural decision record by module and ID.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args getADRInput) (*mcp.CallToolResult, getADROutput, error) {
|
||||
m := idx.FindModule(args.Module)
|
||||
if m == nil {
|
||||
return errorResult("module not found: " + args.Module), getADROutput{}, nil
|
||||
}
|
||||
for _, a := range m.ADRs {
|
||||
if strings.EqualFold(a.ID, args.ID) {
|
||||
out := getADROutput{Module: m.Name, ID: a.ID, Title: a.Title, Body: a.Body}
|
||||
return jsonText(out), out, nil
|
||||
}
|
||||
}
|
||||
return errorResult("ADR not found: " + args.ID + " in module " + args.Module), getADROutput{}, nil
|
||||
})
|
||||
}
|
||||
31
internal/tools/get_changelog.go
Normal file
31
internal/tools/get_changelog.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type getChangelogInput struct {
|
||||
Module string `json:"module" jsonschema:"the module name, e.g. core"`
|
||||
}
|
||||
|
||||
type getChangelogOutput struct {
|
||||
Module string `json:"module"`
|
||||
Changelog string `json:"changelog"`
|
||||
}
|
||||
|
||||
func registerGetChangelog(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "get_changelog",
|
||||
Description: "Return the CHANGELOG.md markdown for one Einherjar module. Use to learn what changed in recent releases and to advise on upgrade-relevant differences.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args getChangelogInput) (*mcp.CallToolResult, getChangelogOutput, error) {
|
||||
m := idx.FindModule(args.Module)
|
||||
if m == nil {
|
||||
return errorResult("module not found: " + args.Module), getChangelogOutput{}, nil
|
||||
}
|
||||
out := getChangelogOutput{Module: m.Name, Changelog: m.Changelog}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
44
internal/tools/get_compliance.go
Normal file
44
internal/tools/get_compliance.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type getComplianceInput struct {
|
||||
Module string `json:"module" jsonschema:"the module name, e.g. core"`
|
||||
}
|
||||
|
||||
type getComplianceOutput struct {
|
||||
Module string `json:"module"`
|
||||
InterfaceAsserts []index.InterfaceAssert `json:"interfaceAsserts"`
|
||||
Tests []index.ComplianceTest `json:"tests"`
|
||||
}
|
||||
|
||||
func registerGetCompliance(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "get_compliance",
|
||||
Description: "Return a module's machine-checked conventions from compliance_test.go: every `var _ Iface = impl` interface assertion (the contracts the module promises to satisfy) and every Test* function (the structural rules the module enforces on itself). Use this before writing or reviewing code in a module to learn which conventions are actively guarded.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args getComplianceInput) (*mcp.CallToolResult, getComplianceOutput, error) {
|
||||
m := idx.FindModule(args.Module)
|
||||
if m == nil {
|
||||
return errorResult("module not found: " + args.Module), getComplianceOutput{}, nil
|
||||
}
|
||||
asserts := m.Compliance.InterfaceAsserts
|
||||
if asserts == nil {
|
||||
asserts = []index.InterfaceAssert{}
|
||||
}
|
||||
tests := m.Compliance.Tests
|
||||
if tests == nil {
|
||||
tests = []index.ComplianceTest{}
|
||||
}
|
||||
out := getComplianceOutput{
|
||||
Module: m.Name,
|
||||
InterfaceAsserts: asserts,
|
||||
Tests: tests,
|
||||
}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
39
internal/tools/get_example.go
Normal file
39
internal/tools/get_example.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type getExampleInput struct {
|
||||
Module string `json:"module" jsonschema:"the module name, e.g. core"`
|
||||
Topic string `json:"topic,omitempty" jsonschema:"optional substring matched against the example title (case-insensitive)"`
|
||||
}
|
||||
|
||||
type getExampleOutput struct {
|
||||
Examples []index.Example `json:"examples"`
|
||||
}
|
||||
|
||||
func registerGetExample(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "get_example",
|
||||
Description: "Return canonical usage examples for a module, extracted from its README. Filter by topic substring (e.g. 'Logger', 'Launcher') to narrow the result.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args getExampleInput) (*mcp.CallToolResult, getExampleOutput, error) {
|
||||
m := idx.FindModule(args.Module)
|
||||
if m == nil {
|
||||
return errorResult("module not found: " + args.Module), getExampleOutput{}, nil
|
||||
}
|
||||
needle := strings.ToLower(args.Topic)
|
||||
out := getExampleOutput{Examples: []index.Example{}}
|
||||
for _, ex := range m.Examples {
|
||||
if needle != "" && !strings.Contains(strings.ToLower(ex.Title), needle) {
|
||||
continue
|
||||
}
|
||||
out.Examples = append(out.Examples, ex)
|
||||
}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
103
internal/tools/get_module.go
Normal file
103
internal/tools/get_module.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type getModuleInput struct {
|
||||
Name string `json:"name" jsonschema:"the module name, e.g. core, web, auth-jwt"`
|
||||
IncludeReadme bool `json:"includeReadme,omitempty" jsonschema:"when true, embed the full README markdown in the response"`
|
||||
}
|
||||
|
||||
type getModuleOutput struct {
|
||||
Name string `json:"name"`
|
||||
ImportPath string `json:"importPath"`
|
||||
Purpose string `json:"purpose"`
|
||||
Doc string `json:"doc"`
|
||||
GoVersion string `json:"goVersion"`
|
||||
DependsOn []string `json:"dependsOn"`
|
||||
SubPackages []index.SubPackage `json:"subPackages"`
|
||||
KeySymbols []symbolHeader `json:"keySymbols"`
|
||||
ADRs []adrHeader `json:"adrs"`
|
||||
Compliance complianceSummary `json:"compliance"`
|
||||
Readme string `json:"readme,omitempty"`
|
||||
}
|
||||
|
||||
type complianceSummary struct {
|
||||
InterfaceAssertCount int `json:"interfaceAssertCount"`
|
||||
TestCount int `json:"testCount"`
|
||||
}
|
||||
|
||||
type symbolHeader struct {
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
SubPackage string `json:"subPackage"`
|
||||
Signature string `json:"signature"`
|
||||
}
|
||||
|
||||
type adrHeader struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
func registerGetModule(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "get_module",
|
||||
Description: "Describe one Einherjar module: sub-packages, key exported symbols (types/interfaces/funcs), and ADRs. Set includeReadme=true to also receive the README markdown.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args getModuleInput) (*mcp.CallToolResult, getModuleOutput, error) {
|
||||
m := idx.FindModule(args.Name)
|
||||
if m == nil {
|
||||
return errorResult("module not found: " + args.Name), getModuleOutput{}, nil
|
||||
}
|
||||
|
||||
key := make([]symbolHeader, 0, len(m.Symbols))
|
||||
for _, sym := range m.Symbols {
|
||||
if sym.Kind == "type" || sym.Kind == "interface" || sym.Kind == "func" {
|
||||
key = append(key, symbolHeader{
|
||||
Kind: sym.Kind, Name: sym.Name, SubPackage: sym.SubPackage, Signature: sym.Signature,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
adrs := make([]adrHeader, 0, len(m.ADRs))
|
||||
for _, a := range m.ADRs {
|
||||
adrs = append(adrs, adrHeader{ID: a.ID, Title: a.Title})
|
||||
}
|
||||
|
||||
subs := make([]index.SubPackage, 0, len(m.SubPackages))
|
||||
for _, sp := range m.SubPackages {
|
||||
if sp.Name == "" {
|
||||
continue
|
||||
}
|
||||
subs = append(subs, sp)
|
||||
}
|
||||
|
||||
deps := m.DependsOn
|
||||
if deps == nil {
|
||||
deps = []string{}
|
||||
}
|
||||
|
||||
out := getModuleOutput{
|
||||
Name: m.Name,
|
||||
ImportPath: m.ImportPath,
|
||||
Purpose: m.Purpose,
|
||||
Doc: m.Doc,
|
||||
GoVersion: m.GoVersion,
|
||||
DependsOn: deps,
|
||||
SubPackages: subs,
|
||||
KeySymbols: key,
|
||||
ADRs: adrs,
|
||||
Compliance: complianceSummary{
|
||||
InterfaceAssertCount: len(m.Compliance.InterfaceAsserts),
|
||||
TestCount: len(m.Compliance.Tests),
|
||||
},
|
||||
}
|
||||
if args.IncludeReadme {
|
||||
out.Readme = m.Readme
|
||||
}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
42
internal/tools/get_symbol.go
Normal file
42
internal/tools/get_symbol.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type getSymbolInput struct {
|
||||
Module string `json:"module" jsonschema:"the module name, e.g. core"`
|
||||
Name string `json:"name" jsonschema:"the symbol name; for methods use Type.Method"`
|
||||
SubPackage string `json:"subPackage,omitempty" jsonschema:"narrow to a specific sub-package, e.g. launcher"`
|
||||
}
|
||||
|
||||
type getSymbolOutput struct {
|
||||
Matches []index.Symbol `json:"matches"`
|
||||
}
|
||||
|
||||
func registerGetSymbol(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "get_symbol",
|
||||
Description: "Fetch full signature, doc comment, and source location for one symbol. Returns every match across sub-packages — use the subPackage filter when ambiguous.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args getSymbolInput) (*mcp.CallToolResult, getSymbolOutput, error) {
|
||||
m := idx.FindModule(args.Module)
|
||||
if m == nil {
|
||||
return errorResult("module not found: " + args.Module), getSymbolOutput{}, nil
|
||||
}
|
||||
out := getSymbolOutput{Matches: []index.Symbol{}}
|
||||
for _, sym := range m.Symbols {
|
||||
if !strings.EqualFold(sym.Name, args.Name) {
|
||||
continue
|
||||
}
|
||||
if args.SubPackage != "" && sym.SubPackage != args.SubPackage {
|
||||
continue
|
||||
}
|
||||
out.Matches = append(out.Matches, sym)
|
||||
}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
40
internal/tools/list_adrs.go
Normal file
40
internal/tools/list_adrs.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type listADRsInput struct {
|
||||
Module string `json:"module,omitempty" jsonschema:"restrict to one module by name"`
|
||||
}
|
||||
|
||||
type listADRsOutput struct {
|
||||
ADRs []adrSummary `json:"adrs"`
|
||||
}
|
||||
|
||||
type adrSummary struct {
|
||||
Module string `json:"module"`
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
func registerListADRs(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "list_adrs",
|
||||
Description: "List architectural decision records across Einherjar. Optionally restrict to one module. Use to discover the rationale behind framework design choices.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args listADRsInput) (*mcp.CallToolResult, listADRsOutput, error) {
|
||||
out := listADRsOutput{ADRs: []adrSummary{}}
|
||||
for _, m := range idx.Modules {
|
||||
if args.Module != "" && m.Name != args.Module {
|
||||
continue
|
||||
}
|
||||
for _, a := range m.ADRs {
|
||||
out.ADRs = append(out.ADRs, adrSummary{Module: m.Name, ID: a.ID, Title: a.Title})
|
||||
}
|
||||
}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
47
internal/tools/list_modules.go
Normal file
47
internal/tools/list_modules.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type listModulesInput struct{}
|
||||
|
||||
type moduleSummary struct {
|
||||
Name string `json:"name"`
|
||||
ImportPath string `json:"importPath"`
|
||||
Purpose string `json:"purpose"`
|
||||
GoVersion string `json:"goVersion"`
|
||||
SubPackages []string `json:"subPackages"`
|
||||
}
|
||||
|
||||
type listModulesOutput struct {
|
||||
Modules []moduleSummary `json:"modules"`
|
||||
}
|
||||
|
||||
func registerListModules(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "list_modules",
|
||||
Description: "List every module of the Einherjar framework with its purpose, import path, Go version, and sub-packages. Use this first to discover what the framework offers.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, _ listModulesInput) (*mcp.CallToolResult, listModulesOutput, error) {
|
||||
out := listModulesOutput{Modules: make([]moduleSummary, 0, len(idx.Modules))}
|
||||
for _, m := range idx.Modules {
|
||||
subs := make([]string, 0, len(m.SubPackages))
|
||||
for _, sp := range m.SubPackages {
|
||||
if sp.Name != "" {
|
||||
subs = append(subs, sp.Name)
|
||||
}
|
||||
}
|
||||
out.Modules = append(out.Modules, moduleSummary{
|
||||
Name: m.Name,
|
||||
ImportPath: m.ImportPath,
|
||||
Purpose: m.Purpose,
|
||||
GoVersion: m.GoVersion,
|
||||
SubPackages: subs,
|
||||
})
|
||||
}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
48
internal/tools/search_symbols.go
Normal file
48
internal/tools/search_symbols.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type searchSymbolsInput struct {
|
||||
Query string `json:"query" jsonschema:"text to match against symbol name, doc comment, sub-package, or module"`
|
||||
Limit int `json:"limit,omitempty" jsonschema:"max results (default 25)"`
|
||||
Module string `json:"module,omitempty" jsonschema:"restrict to one module by name"`
|
||||
Kind string `json:"kind,omitempty" jsonschema:"restrict to one kind: type, interface, func, method, const, var"`
|
||||
}
|
||||
|
||||
type searchSymbolsOutput struct {
|
||||
Results []index.Symbol `json:"results"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
func registerSearchSymbols(s *mcp.Server, idx *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "search_symbols",
|
||||
Description: "Search Einherjar's exported symbols (types, interfaces, funcs, methods, consts, vars) by name or doc text. Optionally filter by module or kind. Use when you need to find where a type or function lives.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args searchSymbolsInput) (*mcp.CallToolResult, searchSymbolsOutput, error) {
|
||||
all := idx.SearchSymbols(args.Query, args.Limit*4+25)
|
||||
filtered := all[:0]
|
||||
for _, sym := range all {
|
||||
if args.Module != "" && sym.Module != args.Module {
|
||||
continue
|
||||
}
|
||||
if args.Kind != "" && sym.Kind != args.Kind {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, sym)
|
||||
}
|
||||
limit := args.Limit
|
||||
if limit <= 0 {
|
||||
limit = 25
|
||||
}
|
||||
if len(filtered) > limit {
|
||||
filtered = filtered[:limit]
|
||||
}
|
||||
out := searchSymbolsOutput{Results: filtered, Total: len(filtered)}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
48
internal/tools/tools.go
Normal file
48
internal/tools/tools.go
Normal file
@@ -0,0 +1,48 @@
|
||||
// Package tools wires Einherjar MCP tools to a server. Each tool lives in its
|
||||
// own file alongside its input and output types.
|
||||
package tools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
// Register binds every tool implemented in this package to s, sharing the
|
||||
// provided index as their backing knowledge.
|
||||
func Register(s *mcp.Server, idx *index.Index) {
|
||||
registerListModules(s, idx)
|
||||
registerGetModule(s, idx)
|
||||
registerSearchSymbols(s, idx)
|
||||
registerGetSymbol(s, idx)
|
||||
registerListADRs(s, idx)
|
||||
registerGetADR(s, idx)
|
||||
registerGetExample(s, idx)
|
||||
registerValidateSnippet(s, idx)
|
||||
registerGetCompliance(s, idx)
|
||||
registerGetChangelog(s, idx)
|
||||
}
|
||||
|
||||
// jsonText returns a CallToolResult whose single text block is the JSON
|
||||
// encoding of v. The same value is also returned as the structured output,
|
||||
// so hosts that surface structured outputs get a typed payload.
|
||||
func jsonText(v any) *mcp.CallToolResult {
|
||||
b, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return &mcp.CallToolResult{
|
||||
IsError: true,
|
||||
Content: []mcp.Content{&mcp.TextContent{Text: "encode error: " + err.Error()}},
|
||||
}
|
||||
}
|
||||
return &mcp.CallToolResult{
|
||||
Content: []mcp.Content{&mcp.TextContent{Text: string(b)}},
|
||||
}
|
||||
}
|
||||
|
||||
func errorResult(msg string) *mcp.CallToolResult {
|
||||
return &mcp.CallToolResult{
|
||||
IsError: true,
|
||||
Content: []mcp.Content{&mcp.TextContent{Text: msg}},
|
||||
}
|
||||
}
|
||||
82
internal/tools/validate_snippet.go
Normal file
82
internal/tools/validate_snippet.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/index"
|
||||
"code.nochebuena.dev/einherjar/mcp/internal/rules"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
type validateSnippetInput struct {
|
||||
Code string `json:"code" jsonschema:"Go source code to validate against Einherjar conventions. A full file is preferred; a partial body will be wrapped automatically."`
|
||||
}
|
||||
|
||||
type validateSnippetOutput struct {
|
||||
Findings []rules.Finding `json:"findings"`
|
||||
Summary string `json:"summary"`
|
||||
}
|
||||
|
||||
func registerValidateSnippet(s *mcp.Server, _ *index.Index) {
|
||||
mcp.AddTool(s, &mcp.Tool{
|
||||
Name: "validate_snippet",
|
||||
Description: "Validate a Go snippet against Einherjar wiring conventions: lifecycle setup, logger configuration, env-var handling, server registration. Findings are advisory, not a substitute for go vet or the project's tests.",
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest, args validateSnippetInput) (*mcp.CallToolResult, validateSnippetOutput, error) {
|
||||
findings := rules.Run(args.Code)
|
||||
if findings == nil {
|
||||
findings = []rules.Finding{}
|
||||
}
|
||||
summary := summarise(findings)
|
||||
out := validateSnippetOutput{Findings: findings, Summary: summary}
|
||||
return jsonText(out), out, nil
|
||||
})
|
||||
}
|
||||
|
||||
func summarise(fs []rules.Finding) string {
|
||||
if len(fs) == 0 {
|
||||
return "No issues found — snippet follows Einherjar conventions."
|
||||
}
|
||||
var errs, warns, infos int
|
||||
for _, f := range fs {
|
||||
switch f.Severity {
|
||||
case rules.SeverityError:
|
||||
errs++
|
||||
case rules.SeverityWarning:
|
||||
warns++
|
||||
case rules.SeverityInfo:
|
||||
infos++
|
||||
}
|
||||
}
|
||||
return pluralise(errs, "error", "errors") + ", " +
|
||||
pluralise(warns, "warning", "warnings") + ", " +
|
||||
pluralise(infos, "note", "notes")
|
||||
}
|
||||
|
||||
func pluralise(n int, singular, plural string) string {
|
||||
if n == 1 {
|
||||
return "1 " + singular
|
||||
}
|
||||
return itoa(n) + " " + plural
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
neg := n < 0
|
||||
if neg {
|
||||
n = -n
|
||||
}
|
||||
var buf [20]byte
|
||||
i := len(buf)
|
||||
for n > 0 {
|
||||
i--
|
||||
buf[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
if neg {
|
||||
i--
|
||||
buf[i] = '-'
|
||||
}
|
||||
return string(buf[i:])
|
||||
}
|
||||
Reference in New Issue
Block a user