chore: initial release v0.1.0

forge-toolkit: хелперы для разработки MCP-серверов на Go.

- toolkit: args/schema/result/env/probe/server
- toolkit/validate: валидаторы синтаксиса
- configreload: live-reload конфига по контент-хэшу
- docs: ARCHITECTURE, quickstart, mcp-contract
- template/ и examples/hello-tool/
- CI (Gitea Actions), лицензия Apache-2.0
This commit is contained in:
Maksim Totmin
2026-09-14 00:23:08 +07:00
commit 9060e5a605
43 changed files with 2581 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
[*.{yml,yaml,json,md}]
indent_style = space
indent_size = 2
[Makefile]
indent_style = tab
+41
View File
@@ -0,0 +1,41 @@
name: ci
# Гейт качества на PR и push в main: vet, тесты с race-детектором, линт,
# gofmt и карантин зависимостей тулкита.
on:
pull_request:
push:
branches: [main]
jobs:
test:
runs-on: backend
container: golang:1.27
steps:
- uses: actions/checkout@v4
- name: vet
run: go vet ./...
- name: test (race)
run: go test -race ./... -count=1
lint:
runs-on: backend
container: golang:1.27
steps:
- uses: actions/checkout@v4
- name: install golangci-lint
run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13.2
- name: lint
run: $(go env GOPATH)/bin/golangci-lint run ./...
- name: gofmt
run: |
unformatted=$(gofmt -l .)
[ -z "$unformatted" ] || { echo "gofmt: требуется форматирование: $unformatted"; exit 1; }
- name: toolkit dependency quarantine
run: |
direct=$(go list -m -f '{{if not .Main}}{{if not .Indirect}}{{.Path}}{{end}}{{end}}' all)
allowed='^(github.com/modelcontextprotocol/go-sdk|gopkg.in/yaml.v3|github.com/BurntSushi/toml)$'
bad=$(echo "$direct" | grep -vE "$allowed" | grep -v '^$')
if [ -n "$bad" ]; then
echo "недопустимые прямые зависимости:"; echo "$bad"; exit 1
fi
+20
View File
@@ -0,0 +1,20 @@
# Сборка и инструменты
/bin/
/dist/
*.test
*.out
# Локальный Go-workspace
go.work
go.work.sum
# Редакторы и ОС
.idea/
.vscode/
*.swp
.DS_Store
# Локальные секреты (шаблон .env.example трекается)
.env
.env.*
!.env.example
+25
View File
@@ -0,0 +1,25 @@
# Конфигурация golangci-lint v2 (формат "2").
#
# Небольшой набор высокосигнальных анализаторов: гейт должен быть полезным,
# а не шумным. Набор расширяется по мере вычищения кодовой базы.
version: "2"
linters:
default: none
enable:
- govet # стандартные проверки компилятора/вет
- ineffassign # бесполезные присваивания
- staticcheck # SA/S/ST: ошибки, упрощения, стиль
- unused # неиспользуемый код
exclusions:
presets:
- std-error-handling
- common-false-positives
formatters:
enable:
- gofmt
issues:
max-issues-per-linter: 0
max-same-issues: 0
+24
View File
@@ -0,0 +1,24 @@
# Changelog
Все значимые изменения документируются здесь. Формат — [Keep a Changelog](https://keepachangelog.com/ru/1.1.0/),
версии — [Semantic Versioning](https://semver.org/lang/ru/).
## [Unreleased]
## [0.1.0] - 2026-09-14
Первый публичный релиз.
### Добавлено
- `toolkit`: разбор аргументов (`RequestArgs`, `Get*`, `RequireString`),
ручные JSON-Schema-хелперы (`Schema`, `StrProps`, `IntProps`, …), результаты
(`Text`, `Error`), `${VAR}`-экспансия (`Expand`), stdio-lifecycle
(`Health`, `Run`).
- `toolkit` probe: протокол эмитированных permission-паттернов
(`RegisterPatternTool`, `WrapProbe`, `IsProbe`).
- `toolkit/validate`: валидаторы синтаксиса (JSON/YAML/TOML/XML/INI/ENV/Dockerfile).
- `configreload`: live-reload конфига по контент-хэшу (`Loader[T]`).
[Unreleased]: https://git.totmin.ru/en2zmax/forge-toolkit/compare/v0.1.0...HEAD
[0.1.0]: https://git.totmin.ru/en2zmax/forge-toolkit/releases/tag/v0.1.0
+85
View File
@@ -0,0 +1,85 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+40
View File
@@ -0,0 +1,40 @@
# Contributing
Спасибо за интерес к forge-toolkit! Ниже — как предложить изменение.
## Окружение
- Go 1.27+.
- `golangci-lint` v2.13.2 (или новее в пределах v2).
```bash
git clone https://git.totmin.ru/en2zmax/forge-toolkit.git
cd forge-toolkit
make test # go test -race ./...
make lint # golangci-lint + gofmt
```
## Требования к изменениям
- Небольшие, сфокусированные PR; один смысловой блок на PR.
- Новый код сопровождается тестами; `make test` и `make lint` должны быть зелёными.
- Публичный API — с doc-комментариями; комментарии по-русски (как в проекте).
- **Границы тулкита неизменны:** только домен-агностичные хелперы и зависимости
stdlib + `go-sdk` (+ `yaml.v3`/`toml` в `validate`). Проверяется `make toolkit-deps`.
Доменная логика и «на будущее» расширения не принимаются.
- Изменения поведения — с записью в [`CHANGELOG.md`](CHANGELOG.md).
## Коммиты
Осмысленный заголовок в стиле Conventional Commits, например:
```
feat(args): поддержать GetFloat
fix(probe): не выполнять действие на probe
docs: уточнить контракт результата
```
## Лицензия вклада
Отправляя PR, вы соглашаетесь на распространение вклада под
[Apache-2.0](LICENSE).
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+42
View File
@@ -0,0 +1,42 @@
# forge-toolkit — сборка, тесты, линт.
GO ?= go
GOLANGCI_LINT ?= golangci-lint
.PHONY: test test-fast lint fmt tidy toolkit-deps ci
# Тесты с race-детектором (основной гейт).
test:
$(GO) test -race ./... -count=1
# Быстрая итерация без race.
test-fast:
$(GO) build ./... && $(GO) vet ./... && $(GO) test ./... -count=1
# Статический анализ + форматирование.
lint:
@command -v $(GOLANGCI_LINT) >/dev/null 2>&1 || { \
echo "golangci-lint не найден: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13.2"; \
exit 1; }
$(GOLANGCI_LINT) run ./...
@unformatted=$$(gofmt -l .); \
if [ -n "$$unformatted" ]; then echo "gofmt: нужно форматирование: $$unformatted"; exit 1; fi
fmt:
gofmt -w .
tidy:
$(GO) mod tidy
# Карантин зависимостей: тулкит обязан оставаться stdlib + go-sdk
# (+ yaml/toml в validate). Любая другая ПРЯМАЯ зависимость — ошибка.
toolkit-deps:
@direct=$$($(GO) list -m -f '{{if not .Main}}{{if not .Indirect}}{{.Path}}{{end}}{{end}}' all); \
allowed='^(github.com/modelcontextprotocol/go-sdk|gopkg.in/yaml.v3|github.com/BurntSushi/toml)$$'; \
bad=$$(echo "$$direct" | grep -vE "$$allowed" | grep -v '^$$'); \
if [ -n "$$bad" ]; then \
echo "недопустимые прямые зависимости (разрешены только go-sdk/yaml/toml):"; \
echo "$$bad"; exit 1; \
fi; \
echo "toolkit-deps: ok"
ci: test lint toolkit-deps
+2
View File
@@ -0,0 +1,2 @@
Forge Toolkit
Copyright 2026 Maksim Totmin
+80
View File
@@ -0,0 +1,80 @@
# forge-toolkit
Хелперы для разработки **MCP-серверов на Go**: разбор аргументов, JSON-Schema,
результаты, stdio-lifecycle, `${VAR}`-экспансия, live-reload конфигов и
протокол эмитированных permission-паттернов (probe).
Подходит для написания своих MCP-инструментов (файлы, БД, HTTP, DevOps и
т.д.) и совместим с любым MCP-клиентом.
## Состав
| Пакет | Назначение |
|---|---|
| `git.totmin.ru/en2zmax/forge-toolkit` | args / schema / result / env / probe / server |
| `git.totmin.ru/en2zmax/forge-toolkit/validate` | валидаторы синтаксиса (JSON/YAML/TOML/XML/INI/ENV/Dockerfile) |
| `git.totmin.ru/en2zmax/forge-toolkit/configreload` | live-reload конфига по контент-хэшу |
Зависимости тулкита намеренно минимальны: stdlib + официальный
[`modelcontextprotocol/go-sdk`](https://github.com/modelcontextprotocol/go-sdk)
(+ `yaml.v3`/`toml` в подпакете `validate`). Это фиксируется в CI
(`make toolkit-deps`).
## Установка
Модуль размещён на self-hosted Gitea, поэтому `go get` идёт напрямую, мимо
`proxy.golang.org`:
```bash
export GOPRIVATE=git.totmin.ru
go get git.totmin.ru/en2zmax/forge-toolkit@latest
```
## Быстрый старт
```go
package main
import (
"context"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"git.totmin.ru/en2zmax/forge-toolkit"
)
func main() {
if toolkit.Health() {
return
}
_ = toolkit.Run("my-server", func(s *mcp.Server) {
mcp.AddTool(s, &mcp.Tool{
Name: "get_time",
Description: "Текущее время сервера (UTC). Read-only.",
InputSchema: toolkit.Schema(nil, nil),
}, func(context.Context, *mcp.CallToolRequest, struct{}) (*mcp.CallToolResult, any, error) {
return toolkit.Text(time.Now().UTC().Format(time.RFC3339)), nil, nil
})
})
}
```
## Документация
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — контракт и правила сервера.
- [`docs/quickstart.md`](docs/quickstart.md) — первый инструмент за 10 минут.
- [`docs/mcp-contract.md`](docs/mcp-contract.md) — формат результата и probe на проводе.
- [`template/`](template/) — готовый каркас сервера.
- [`examples/hello-tool/`](examples/hello-tool/) — минимальный рабочий пример.
## Разработка
```bash
make test # go test -race ./...
make lint # golangci-lint + gofmt
make tidy # go mod tidy
```
## Лицензия
Apache-2.0 — см. [`LICENSE`](LICENSE).
+25
View File
@@ -0,0 +1,25 @@
# Security Policy
## Поддерживаемые версии
Исправления безопасности выходят для последней минорной версии.
## Как сообщить об уязвимости
**Не создавайте публичный issue.** Напишите на `security@totmin.ru` и укажите:
- описание уязвимости и потенциальное влияние;
- шаги воспроизведения или PoC;
- затронутые версии/пакеты;
- по желанию — предлагаемое исправление.
Мы подтвердим получение в течение нескольких рабочих дней и согласуем сроки
раскрытия после выпуска исправления.
## Область
forge-toolkit — библиотека хелперов; она не выполняет ввод-вывод сама по
себе. Уязвимости домена (политики доступа, jail, SQL-guard) относятся к
конкретным MCP-серверам, построенным на тулките, и рассматриваются в их
репозиториях. В этом репозитории рассматриваются проблемы самого тулкита:
парсинг аргументов/схем/конфигов, экспансия `${VAR}`, probe-протокол.
+150
View File
@@ -0,0 +1,150 @@
package toolkit
import (
"encoding/json"
"fmt"
"strconv"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// RequestArgs распаковывает сырые аргументы tool-вызова в map[string]any.
// Битый JSON / пустые аргументы → пустая карта (валидация — в хендлерах).
func RequestArgs(req *mcp.CallToolRequest) map[string]any {
if req == nil || req.Params == nil || len(req.Params.Arguments) == 0 {
return map[string]any{}
}
var a map[string]any
if err := json.Unmarshal(req.Params.Arguments, &a); err != nil {
return map[string]any{}
}
return a
}
// GetString возвращает строковый аргумент или def. Не-строки приводятся к
// строке через %v (терпимость к числам/булевым от моделей).
func GetString(args map[string]any, key, def string) string {
v, ok := args[key]
if !ok || v == nil {
return def
}
if s, ok := v.(string); ok {
return s
}
return fmt.Sprintf("%v", v)
}
// RequireString возвращает непустой строковый аргумент или ошибку.
func RequireString(args map[string]any, key string) (string, error) {
v, ok := args[key]
if !ok || v == nil {
return "", fmt.Errorf("missing required argument '%s'", key)
}
s, ok := v.(string)
if !ok || s == "" {
return "", fmt.Errorf("argument '%s' must be a non-empty string", key)
}
return s, nil
}
// GetInt возвращает целочисленный аргумент или def. Принимает float64
// (обычный JSON-числовой тип), int и строку с числом.
func GetInt(args map[string]any, key string, def int) int {
v, ok := args[key]
if !ok || v == nil {
return def
}
switch n := v.(type) {
case float64:
return int(n)
case int:
return n
case string:
if i, err := strconv.Atoi(n); err == nil {
return i
}
}
return def
}
// GetBool возвращает булев аргумент или def.
func GetBool(args map[string]any, key string, def bool) bool {
v, ok := args[key]
if !ok || v == nil {
return def
}
if b, ok := v.(bool); ok {
return b
}
return def
}
// GetStringArray возвращает непустой срез непустых строк. ok=false, если
// аргумента нет, он не массив или после фильтрации пуст.
func GetStringArray(args map[string]any, key string) ([]string, bool) {
v, ok := args[key]
if !ok || v == nil {
return nil, false
}
arr, ok := v.([]any)
if !ok || len(arr) == 0 {
return nil, false
}
var out []string
for _, item := range arr {
if s, ok := item.(string); ok && s != "" {
out = append(out, s)
}
}
if len(out) == 0 {
return nil, false
}
return out, true
}
// GetIntArray возвращает непустой срез int (float64/int элементы).
func GetIntArray(args map[string]any, key string) ([]int, bool) {
v, ok := args[key]
if !ok || v == nil {
return nil, false
}
arr, ok := v.([]any)
if !ok || len(arr) == 0 {
return nil, false
}
var out []int
for _, item := range arr {
switch n := item.(type) {
case float64:
out = append(out, int(n))
case int:
out = append(out, n)
}
}
if len(out) == 0 {
return nil, false
}
return out, true
}
// GetStringMap разбирает объект со строковыми значениями (напр. заголовки).
func GetStringMap(args map[string]any, key string) map[string]string {
v, ok := args[key]
if !ok || v == nil {
return nil
}
m, ok := v.(map[string]any)
if !ok || len(m) == 0 {
return nil
}
out := make(map[string]string, len(m))
for k, val := range m {
if s, ok := val.(string); ok {
out[k] = s
}
}
if len(out) == 0 {
return nil
}
return out
}
+105
View File
@@ -0,0 +1,105 @@
package toolkit
import (
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestRequestArgs(t *testing.T) {
req := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{
Arguments: []byte(`{"path":"/tmp/x","n":3}`),
}}
got := RequestArgs(req)
if got["path"] != "/tmp/x" {
t.Errorf("path = %v", got["path"])
}
if RequestArgs(nil)["missing"] != nil {
t.Error("nil request must yield empty map")
}
bad := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{Arguments: []byte(`{not json`)}}
if len(RequestArgs(bad)) != 0 {
t.Error("bad json must yield empty map")
}
}
func TestScalarGetters(t *testing.T) {
args := map[string]any{
"s": "hello",
"n": float64(42),
"ns": "17",
"b": true,
"null": nil,
}
if got := GetString(args, "s", "def"); got != "hello" {
t.Errorf("GetString = %q", got)
}
if got := GetString(args, "n", "def"); got != "42" {
t.Errorf("GetString(number) = %q", got)
}
if got := GetString(args, "missing", "def"); got != "def" {
t.Errorf("GetString(missing) = %q", got)
}
if got := GetInt(args, "n", 0); got != 42 {
t.Errorf("GetInt(float64) = %d", got)
}
if got := GetInt(args, "ns", 0); got != 17 {
t.Errorf("GetInt(string) = %d", got)
}
if got := GetInt(args, "missing", 9); got != 9 {
t.Errorf("GetInt(default) = %d", got)
}
if !GetBool(args, "b", false) {
t.Error("GetBool = false, want true")
}
if GetBool(args, "missing", true) != true {
t.Error("GetBool(default) = false")
}
}
func TestRequireString(t *testing.T) {
if _, err := RequireString(map[string]any{}, "x"); err == nil {
t.Error("missing arg must error")
}
if _, err := RequireString(map[string]any{"x": ""}, "x"); err == nil {
t.Error("empty arg must error")
}
if v, err := RequireString(map[string]any{"x": "ok"}, "x"); err != nil || v != "ok" {
t.Errorf("RequireString = (%q, %v)", v, err)
}
}
func TestArrayGetters(t *testing.T) {
args := map[string]any{
"strs": []any{"a", "", "b", 3},
"ints": []any{float64(1), 2, "x"},
}
strs, ok := GetStringArray(args, "strs")
if !ok || len(strs) != 2 || strs[0] != "a" || strs[1] != "b" {
t.Errorf("GetStringArray = (%v, %v)", strs, ok)
}
ints, ok := GetIntArray(args, "ints")
if !ok || len(ints) != 2 || ints[0] != 1 || ints[1] != 2 {
t.Errorf("GetIntArray = (%v, %v)", ints, ok)
}
if _, ok := GetStringArray(args, "missing"); ok {
t.Error("missing array must be ok=false")
}
if _, ok := GetStringArray(map[string]any{"e": []any{}}, "e"); ok {
t.Error("empty array must be ok=false")
}
}
func TestGetStringMap(t *testing.T) {
args := map[string]any{"h": map[string]any{"A": "1", "B": 2}}
got := GetStringMap(args, "h")
if got["A"] != "1" {
t.Errorf("GetStringMap = %v", got)
}
if _, exists := got["B"]; exists {
t.Error("non-string value must be dropped")
}
if GetStringMap(args, "missing") != nil {
t.Error("missing map must be nil")
}
}
+104
View File
@@ -0,0 +1,104 @@
// Package configreload — общий мини-либ для live-reload конфигов MCP-серверов
// (контракт per-tenant config + live-reload, см. docs/ARCHITECTURE.md):
// stdlib-only, без внешних зависимостей, поэтому не тащит лишнего.
//
// Идея: каждый сервер держит свой per-agent конфиг
// <FORGE_TENANT_CONFIG>/<tool>.json. Loader[T] читает файл, сверяет контент
// по sha256 (единственный источник истины — контент-хэш, а не mtime) и
// перечитывает/парсит, только если содержимое изменилось. Загружается лениво
// и потокобезопасно.
package configreload
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"sync"
)
// ErrNotFound — файл конфига отсутствует (или удалён). Такой конфиг следует
// трактовать как "нет тенант-конфига" (сервер сам решит фолбэк на дефолт).
var ErrNotFound = errors.New("configreload: config file not found")
// Loader — ленивый, потокобезопасный загрузчик конфига с last-good.
// T — тип распарсенного конфига; parse — билдер из сырых байтов.
type Loader[T any] struct {
path string
parse func([]byte) (T, error)
mu sync.Mutex
current T
hash string
got bool
parseErr error
}
// New создаёт загрузчик конфига path с парсером parse.
func New[T any](path string, parse func([]byte) (T, error)) *Loader[T] {
return &Loader[T]{path: path, parse: parse}
}
// Path возвращает путь конфига.
func (l *Loader[T]) Path() string { return l.path }
// Get возвращает актуальный конфиг, перечитывая файл, только если его
// содержимое изменилось (sha256). Возвращает:
// - (value, nil) — актуальный конфиг;
// - (lastGood, err) — файл изменился к невалидному (parseErr) или чтение
// дало ошибку: возвращается последний рабочий конфиг + ошибка, чтобы
// вызывающий мог залогировать и продолжить со старым;
// - (zero, ErrNotFound) — файл отсутствует/удалён (кэш сброшен);
// - (zero, err) — прочие ошибки чтения.
//
// Ключ: контент-хэш — истина. Даже если mtime/размер "не изменились", мы не
// пропускаем чтение — файл маленький, а ложь о контенте опаснее корректного
// поведения.
func (l *Loader[T]) Get() (T, error) {
l.mu.Lock()
defer l.mu.Unlock()
data, err := os.ReadFile(l.path)
if err != nil {
if os.IsNotExist(err) {
// Конфиг удалён — сбрасываем кэш, сообщаем "нет конфига".
l.got, l.hash, l.parseErr = false, "", nil
var zero T
return zero, fmt.Errorf("%w: %s", ErrNotFound, l.path)
}
return l.lastGood(fmt.Errorf("configreload: read %s: %w", l.path, err))
}
sum := sha256.Sum256(data)
hash := hex.EncodeToString(sum[:])
if l.got && hash == l.hash {
// Содержимое не изменилось — быстрый путь. Если последний парсинг
// был с ошибкой, возвращаем last-good (не затираем его).
return l.current, l.parseErr
}
val, perr := l.parse(data)
if perr != nil {
// Файл изменился к невалидному содержимому: сохраняем last-good,
// фиксируем ошибку парсинга (следующий Get с тем же хэшем вернёт её).
l.parseErr = perr
return l.lastGood(fmt.Errorf("configreload: parse %s: %w", l.path, perr))
}
l.current = val
l.hash = hash
l.got = true
l.parseErr = nil
return val, nil
}
// lastGood возвращает последний рабочий конфиг (если был) вместе с err, чтобы
// вызывающий мог залогировать и продолжить работу со старым значением.
func (l *Loader[T]) lastGood(err error) (T, error) {
if l.got {
return l.current, err
}
var zero T
return zero, err
}
+110
View File
@@ -0,0 +1,110 @@
package configreload
import (
"errors"
"os"
"path/filepath"
"testing"
)
func write(t *testing.T, dir, content string) string {
t.Helper()
p := filepath.Join(dir, "cfg.json")
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
t.Fatalf("write: %v", err)
}
return p
}
func parse(cfg map[string]string) func([]byte) (map[string]string, error) {
return func(b []byte) (map[string]string, error) {
if len(b) == 0 {
return nil, errors.New("empty")
}
return map[string]string{"v": string(b)}, nil
}
}
func TestLoader_CachesUntilContentChanges(t *testing.T) {
dir := t.TempDir()
p := write(t, dir, "one")
l := New(p, parse(nil))
if v, err := l.Get(); err != nil || v["v"] != "one" {
t.Fatalf("first get: %v %v", v, err)
}
// Не изменилось — отдаётся из кэша (нет системных вызовов на парсинг).
if v, err := l.Get(); err != nil || v["v"] != "one" {
t.Fatalf("cached get: %v %v", v, err)
}
// Изменилось содержимое на то же по размеру → хэш ловит.
if err := os.WriteFile(p, []byte("two"), 0o600); err != nil {
t.Fatalf("rewrite: %v", err)
}
if v, err := l.Get(); err != nil || v["v"] != "two" {
t.Fatalf("after change: %v %v", v, err)
}
}
func TestLoader_LastGoodOnInvalid(t *testing.T) {
dir := t.TempDir()
p := write(t, dir, "good")
l := New(p, parse(nil))
if _, err := l.Get(); err != nil {
t.Fatalf("get: %v", err)
}
// Пишем невалидный (пустой) файл — парсер вернёт ошибку => last-good.
if err := os.WriteFile(p, []byte(""), 0o600); err != nil {
t.Fatalf("write empty: %v", err)
}
v, err := l.Get()
if err == nil {
t.Fatal("expected parse error")
}
if v["v"] != "good" {
t.Fatalf("expected last-good value, got %v", v)
}
}
func TestLoader_NotFoundReset(t *testing.T) {
dir := t.TempDir()
p := write(t, dir, "x")
l := New(p, parse(nil))
if _, err := l.Get(); err != nil {
t.Fatalf("get: %v", err)
}
if err := os.Remove(p); err != nil {
t.Fatalf("remove: %v", err)
}
if _, err := l.Get(); !errors.Is(err, ErrNotFound) {
t.Fatalf("expected ErrNotFound, got %v", err)
}
// Восстановили файл — снова загружается.
write(t, dir, "y")
p2 := filepath.Join(dir, "cfg.json")
if v, err := l.Get(); err != nil || v["v"] != "y" {
t.Fatalf("after restore: %v %v", v, err)
} else if p2 == "" {
t.Fatal("unreachable")
}
}
func TestLoader_Concurrent(t *testing.T) {
dir := t.TempDir()
p := write(t, dir, "start")
l := New(p, parse(nil))
done := make(chan struct{})
for i := 0; i < 20; i++ {
go func() {
defer func() { done <- struct{}{} }()
_, _ = l.Get()
}()
}
for i := 0; i < 20; i++ {
<-done
}
// После конкурентных чтений — кэш валиден.
if v, err := l.Get(); err != nil || v["v"] != "start" {
t.Fatalf("after concurrent: %v %v", v, err)
}
}
+11
View File
@@ -0,0 +1,11 @@
// Package toolkit — общий слой для MCP-серверов на Go: разбор аргументов,
// JSON-Schema, результаты, forge-probe (эмитированные permission-паттерны),
// ${VAR}-экспансия и stdio-lifecycle. Дополняет пакет configreload
// (live-reload конфигов).
//
// ГРАНИЦЫ (см. docs/ARCHITECTURE.md и README.md): пакет содержит ТОЛЬКО
// домен-агностичные хелперы и зависит только от stdlib + go-sdk
// (+ yaml/toml в подпакете validate). Никакой доменной логики
// (manager/policy/netpolicy/SQL-guard) здесь быть не должно — проверяется
// целью `make toolkit-deps`.
package toolkit
+192
View File
@@ -0,0 +1,192 @@
# Архитектура MCP-серверов на forge-toolkit
> **Кому:** разработчику, который пишет MCP-сервер на Go с этим тулкитом.
> После прочтения ты должен уметь написать сервер любого домена: файлы, БД,
> HTTP, DevOps и т.д.
Эталон рядом: [`template/`](../template) (каркас) и
[`examples/hello-tool/`](../examples/hello-tool) (минимальный рабочий пример).
---
## 1. Что такое сервер на forge-toolkit
MCP-сервер — **самостоятельная консольная программа**: читает JSON-RPC из
stdin, пишет в stdout. Один сервер решает **одну задачу** и даёт один или
несколько инструментов. Никакого «заодно могу и…».
Сервер собирается из:
- **каркаса** — `toolkit` / `toolkit/validate` / `configreload` (домен-агностичные
хелперы);
- **домена** — код конкретной задачи (политики, клиенты, маппинг аргументов).
Домен живёт отдельно от каркаса; каркас не расширяется «на будущее».
---
## 2. Три столпа
1. **stdio-only.** Транспорт — stdin/stdout (`mcp.StdioTransport`). Сервер не
поднимает HTTP/SSE/TCP и не заводит session-pool: хост сам решает, как
запускать процесс (один на сервер, один на агента и т.д.).
2. **Один потокобезопасный Manager.** Состояние процесса — один объект-
диспетчер. Если он изменяемый (пулы соединений, кэши) — под мутексом
(`sync.RWMutex`): инструменты вызываются конкурентно.
3. **Ручные схемы.** Инструмент объявляется явно:
`&mcp.Tool{Name, Description, InputSchema}` + обработчик. `InputSchema` —
JSON Schema 2020-12, собирается хелперами `toolkit.Schema/StrProps/...`.
---
## 3. Жизненный цикл `main.go`
```go
func main() {
if toolkit.Health() { // --health → печатает "ok" и выходит (дешёво)
return
}
mgr := mydomain.NewManager() // один Manager на процесс
defer mgr.Close()
if err := toolkit.Run("my-server", func(s *mcp.Server) {
tools.RegisterAll(s, mgr)
}); err != nil {
fmt.Fprintf(os.Stderr, "my-server: %v\n", err)
os.Exit(1)
}
}
```
`toolkit.Run` поднимает `mcp.NewServer` и stdio-цикл с graceful shutdown по
`SIGINT`/`SIGTERM`.
---
## 4. Инструмент: объявление и схема
Имя инструмента — **без префикса сервера** (`read_file`, `run_query`): хост
добавит свой префикс при регистрации.
```go
mcp.AddTool(s, &mcp.Tool{
Name: "read_file",
Description: "Читает файл внутри разрешённых корней. Read-only.",
InputSchema: toolkit.Schema(map[string]any{
"path": toolkit.StrProps("путь относительно корня", true),
}, []string{"path"}),
}, func(ctx context.Context, req *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, any, error) {
args := toolkit.RequestArgs(req)
path, err := toolkit.RequireString(args, "path")
if err != nil {
return toolkit.Error(err.Error()), nil, nil
}
// ... доменная работа ...
return toolkit.Text("..."), nil, nil
})
```
`properties` в схеме — всегда объект (даже пустой): часть провайдеров
отклоняет `"properties": null`.
---
## 5. Результат и ошибки
`mcp.CallToolResult`:
- успех — `toolkit.Text(msg)`;
- **доменная** ошибка (модель должна исправиться) — `toolkit.Error(msg)`
(`IsError=true`), цикл агента продолжается;
- **инфраструктурный** сбой — вернуть Go-`error`: вызов считается неудачным.
Правило: всё, что модель может поправить (неверный аргумент, не найдено,
недостаточно прав) — `toolkit.Error`; всё, что сломано на стороне сервера
(диск, сеть, паника) — Go-`error`.
---
## 6. Хелперы аргументов
`toolkit.RequestArgs(req)` → `map[string]any`. Далее:
| Хелпер | Назначение |
|---|---|
| `GetString(args, key, def)` | строка (не-строки приводятся через `%v`) |
| `RequireString(args, key)` | непустая строка или ошибка |
| `GetInt(args, key, def)` | int (принимает `float64`/строку) |
| `GetBool(args, key, def)` | bool |
| `GetStringArray` / `GetIntArray` | непустые срезы |
| `GetStringMap(args, key)` | объект строк (например, заголовки) |
Валидация аргументов — в обработчике, а не в схеме: схема подсказывает
модели, обработчик — источник истины.
---
## 7. Конфиг и live-reload
Сервер читает свой конфиг из файла (по флагу `-config`) и/или из каталога
тенанта `FORGE_TENANT_CONFIG/<server>.json`. Для перечитывания на лету —
`configreload`:
```go
loader := configreload.New(path, parseConfig) // сверяет контент по sha256
cfg, err := loader.Get() // перечитывает только при изменении
```
`${VAR}` в конфиге разворачивается через `toolkit.Expand`; отсутствующая
переменная даёт пустую строку — дальнейшая валидация отвергнет пустое
обязательное поле (fail-closed).
---
## 8. Безопасность
- **Минимум прав по умолчанию.** Политики задают явные allow/deny; дефолт —
запрет, а не разрешение.
- **Ограничивай область.** Пути — внутри разрешённых корней (jail); SQL —
только параметризованный и read-only там, где это возможно; сеть — только
разрешённые схемы/хосты.
- **Ограничивай время.** Любая внешняя операция — с `context` и таймаутом;
инструмент не должен подвешивать сервер.
- **Секреты — только из окружения** (`${VAR}`), не в конфиге и не в коде.
---
## 9. Approval и probe (эмитированные паттерны)
Инструменты, выполняющие side-effect, могут объявить **permission-паттерны**:
хост использует их для политики одобрения, а probe-вызов позволяет узнать
паттерны **без выполнения действия**.
```go
toolkit.RegisterPatternTool(s, tool, func(args map[string]any) (patterns, always []string) {
return []string{"write:" + toolkit.GetString(args, "path", "")}, nil
}, handler)
```
Probe-вызов (`_meta["forge.permission_patterns"]=true`) возвращает паттерны в
`_meta` и **не выполняет** действие (см. [`mcp-contract.md`](mcp-contract.md)).
---
## 10. Тестирование
- Юнит-тесты домена и парсинга конфига; `go test -race ./...`.
- Для обработчиков — прямой вызов с собранным `*mcp.CallToolRequest`.
- Проверяй probe: действие не выполняется, паттерны возвращаются.
---
## 11. Definition of Done
1. Отдельный Go-модуль, stdio-only, один потокобезопасный Manager.
2. `main.go` использует `toolkit.Health()` и `toolkit.Run(...)`.
3. Каркас — из `toolkit`/`toolkit/validate`/`configreload`; домен — в своём пакете.
4. Конфиг с `${VAR}` (fail-closed) и live-reload; статический `-config` — фолбэк.
5. Side-effecting инструменты объявляют паттерны через `RegisterPatternTool`;
дефолт политики — least-privilege.
6. Юнит-тесты; `go test -race ./...` зелёный.
7. `README.md`: инструменты, безопасность, подключение, схема approval.
8. `go mod tidy`, `golangci-lint run ./...`, `gofmt` — чисто.
+71
View File
@@ -0,0 +1,71 @@
# Контракт на проводе
Сервер — стандартный MCP-сервер (JSON-RPC 2.0 через stdio). Здесь зафиксировано
то, что важно для корректной работы с хостом: формат результата и
forge-специфичный probe.
## `CallToolResult`
Успех:
```json
{ "content": [ { "type": "text", "text": "..." } ] }
```
Доменная ошибка (модель должна увидеть и исправить):
```json
{ "content": [ { "type": "text", "text": "не найдено: ..." } ], "isError": true }
```
- `isError: true` — ошибка **инструмента**, а не транспорта: цикл агента
продолжается.
- Инфраструктурный сбой возвращается как Go-`error` (JSON-RPC error), а не
как `isError`.
Хелперы: `toolkit.Text`, `toolkit.Error`.
## Probe: эмитированные permission-паттерны
Инструменты с побочными эффектами могут сообщать хосту **канонические
паттерны** доступа. Хост вызывает инструмент в режиме probe, получает
паттерны и применяет политику одобрения, **не выполняя действие**.
Запрос probe — стандартное поле `_meta` вызова:
```json
{
"method": "tools/call",
"params": {
"name": "write_file",
"arguments": { "path": "a.txt", "content": "hi" },
"_meta": { "forge.permission_patterns": true }
}
}
```
Ответ probe — паттерны в `_meta`, без побочного эффекта:
```json
{
"content": [],
"_meta": {
"forge.patterns": ["write:a.txt"],
"forge.always": []
}
}
```
Ключи (константы в `toolkit/probe.go`):
| Ключ | Смысл |
|---|---|
| `forge.permission_patterns` | флаг запроса probe |
| `forge.patterns` | паттерны, зависящие от аргументов |
| `forge.always` | паттерны, действующие всегда |
| `forge.supports_permission_patterns` | флаг в `Tool.Meta`: сервер поддерживает probe |
Инструменты без побочных эффектов probe не поддерживают — хост не шлёт им
probe-вызов.
Хелперы: `toolkit.RegisterPatternTool`, `toolkit.WrapProbe`, `toolkit.IsProbe`.
+123
View File
@@ -0,0 +1,123 @@
# Быстрый старт: первый инструмент за 10 минут
Сделаем MCP-сервер с одним инструментом `echo`, который возвращает переданный
текст.
## 1. Модуль
```bash
mkdir my-mcp && cd my-mcp
go mod init example.com/my-mcp
export GOPRIVATE=git.totmin.ru
go get git.totmin.ru/en2zmax/forge-toolkit@latest
go get github.com/modelcontextprotocol/go-sdk@latest
```
## 2. Инструмент
`internal/tools/tools.go`:
```go
package tools
import (
"context"
"github.com/modelcontextprotocol/go-sdk/mcp"
"git.totmin.ru/en2zmax/forge-toolkit"
)
func RegisterAll(s *mcp.Server) {
mcp.AddTool(s, &mcp.Tool{
Name: "echo",
Description: "Возвращает переданный текст. Без побочных эффектов.",
InputSchema: toolkit.Schema(map[string]any{
"text": toolkit.StrProps("текст для возврата", true),
}, []string{"text"}),
}, handleEcho)
}
func handleEcho(_ context.Context, req *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, any, error) {
text, err := toolkit.RequireString(toolkit.RequestArgs(req), "text")
if err != nil {
return toolkit.Error(err.Error()), nil, nil
}
return toolkit.Text(text), nil, nil
}
```
## 3. `main.go`
```go
package main
import (
"fmt"
"os"
"example.com/my-mcp/internal/tools"
"github.com/modelcontextprotocol/go-sdk/mcp"
"git.totmin.ru/en2zmax/forge-toolkit"
)
func main() {
if toolkit.Health() {
return
}
if err := toolkit.Run("my-mcp", func(s *mcp.Server) {
tools.RegisterAll(s)
}); err != nil {
fmt.Fprintf(os.Stderr, "my-mcp: %v\n", err)
os.Exit(1)
}
}
```
## 4. Сборка и проверка
```bash
go mod tidy
go build -o my-mcp .
./my-mcp --health # → ok
```
## 5. Подключение
**Любой MCP-клиент** (Claude Desktop, Cursor и т.п.) — как обычный stdio-сервер:
```json
{
"mcpServers": {
"my-mcp": { "command": "/abs/path/my-mcp" }
}
}
```
**Агентная платформа Forge** — сервер объявляется оператором в конфиге, а
агент подключает его по имени. Например, глобально:
```json
{
"mcp": {
"servers": {
"my-mcp": { "command": "/abs/path/my-mcp", "args": [] }
}
}
}
```
и в агенте:
```yaml
mcp_servers:
- my-mcp
```
Инструмент станет доступен модели как `my-mcp__echo`.
## Дальше
- Контракт и правила — [`ARCHITECTURE.md`](ARCHITECTURE.md).
- Формат результата/probe — [`mcp-contract.md`](mcp-contract.md).
- Каркас с конфигом и Makefile — [`../template/`](../template).
+22
View File
@@ -0,0 +1,22 @@
package toolkit
import (
"os"
"regexp"
)
// envVarRe — плейсхолдер ${VAR} (та же конвенция, что в config.json сервера).
var envVarRe = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}`)
// Expand разворачивает ${VAR} в сырых байтах конфига. Отсутствующая
// переменная заменяется пустой строкой: дальнейшая валидация отвергнет
// пустое обязательное поле (fail-closed), а не подставит мусор.
//
// Это lax-вариант. Для строгих случаев (DSN с доменными ошибками) сервер
// держит собственный strict-экспандер — не обобщаем преждевременно.
func Expand(data []byte) []byte {
return envVarRe.ReplaceAllFunc(data, func(m []byte) []byte {
name := string(m[2 : len(m)-1]) // вырезаем имя из "${...}"
return []byte(os.Getenv(name))
})
}
+36
View File
@@ -0,0 +1,36 @@
package toolkit
import (
"os"
"testing"
)
func TestExpand(t *testing.T) {
t.Setenv("TOOLKIT_TEST_VAR", "value")
got := string(Expand([]byte(`{"x":"${TOOLKIT_TEST_VAR}","y":"static"}`)))
want := `{"x":"value","y":"static"}`
if got != want {
t.Errorf("Expand = %q, want %q", got, want)
}
// Неизвестная переменная → пустая строка (fail-closed далее по валидации).
os.Unsetenv("TOOLKIT_TEST_MISSING")
got = string(Expand([]byte(`"${TOOLKIT_TEST_MISSING}"`)))
if got != `""` {
t.Errorf("Expand(missing) = %q, want empty", got)
}
}
func TestHealth(t *testing.T) {
orig := os.Args
defer func() { os.Args = orig }()
os.Args = []string{"prog", "--health"}
if !Health() {
t.Error("Health() = false with --health")
}
os.Args = []string{"prog", "-config", "x"}
if Health() {
t.Error("Health() = true without --health")
}
}
+17
View File
@@ -0,0 +1,17 @@
# hello-tool
Минимальный MCP-сервер на `forge-toolkit`: один инструмент `echo`.
```bash
go mod tidy
go build -o hello-tool .
./hello-tool --health # → ok
```
Подключение — как к любому stdio MCP-серверу:
```json
{ "mcpServers": { "hello-tool": { "command": "/abs/path/hello-tool" } } }
```
Пошаговый разбор — [`../../docs/quickstart.md`](../../docs/quickstart.md).
+21
View File
@@ -0,0 +1,21 @@
module example.com/hello-tool
go 1.27.0
require (
git.totmin.ru/en2zmax/forge-toolkit v0.1.0
github.com/modelcontextprotocol/go-sdk v1.7.0
)
require (
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/time v0.15.0 // indirect
)
replace git.totmin.ru/en2zmax/forge-toolkit => ../..
+24
View File
@@ -0,0 +1,24 @@
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
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.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
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/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
@@ -0,0 +1,25 @@
package tools
import (
"context"
"git.totmin.ru/en2zmax/forge-toolkit"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// RegisterAll регистрирует инструменты сервера.
func RegisterAll(s *mcp.Server) {
mcp.AddTool(s, &mcp.Tool{
Name: "echo",
Description: "Возвращает переданный текст. Без побочных эффектов.",
InputSchema: toolkit.Schema(map[string]any{
"text": toolkit.StrProps("текст для возврата", true),
}, []string{"text"}),
}, func(_ context.Context, req *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, any, error) {
text, err := toolkit.RequireString(toolkit.RequestArgs(req), "text")
if err != nil {
return toolkit.Error(err.Error()), nil, nil
}
return toolkit.Text(text), nil, nil
})
}
+24
View File
@@ -0,0 +1,24 @@
// Command hello-tool — минимальный MCP-сервер на forge-toolkit.
package main
import (
"fmt"
"os"
"example.com/hello-tool/internal/tools"
"git.totmin.ru/en2zmax/forge-toolkit"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func main() {
if toolkit.Health() {
return
}
if err := toolkit.Run("hello-tool", func(s *mcp.Server) {
tools.RegisterAll(s)
}); err != nil {
fmt.Fprintf(os.Stderr, "hello-tool: %v\n", err)
os.Exit(1)
}
}
+20
View File
@@ -0,0 +1,20 @@
module git.totmin.ru/en2zmax/forge-toolkit
go 1.27.0
require (
github.com/BurntSushi/toml v1.6.0
github.com/modelcontextprotocol/go-sdk v1.7.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/time v0.15.0 // indirect
)
+30
View File
@@ -0,0 +1,30 @@
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
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.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
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/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+67
View File
@@ -0,0 +1,67 @@
package toolkit
import (
"context"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// Ключи forge-специфичных метаданных в стандартном поле `_meta` (SEP-2575).
// MCP-хост forge, вызвав инструмент с флагом probe, ожидает, что сервер НЕ
// выполнит действие, а вернёт эмитированные permission-паттерны. Константы
// дублируются на стороне хоста: хост не импортирует этот пакет.
const (
metaProbeKey = "forge.permission_patterns"
metaPatternsKey = "forge.patterns"
metaAlwaysKey = "forge.always"
// metaCapabilityKey — флаг в Tool.Meta: сервер объявляет поддержку
// forge-протокола эмитированных паттернов. Хост проверяет его перед
// probe, чтобы не слать probe серверам без поддержки.
metaCapabilityKey = "forge.supports_permission_patterns"
)
// PatternsFn вычисляет эмитированные permission-паттерны и безопасные
// префиксы "always" по аргументам инструмента. nil — инструмент паттернов
// не эмитирует (хост применит политику по умолчанию).
type PatternsFn func(args map[string]any) (patterns, always []string)
// WrapProbe оборачивает handler, перехватывая probe-запрос хоста: вместо
// выполнения действия возвращает `_meta` с паттернами.
func WrapProbe(h mcp.ToolHandler, fn PatternsFn) mcp.ToolHandler {
return func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
if IsProbe(req) {
var patterns, always []string
if fn != nil {
patterns, always = fn(RequestArgs(req))
}
return &mcp.CallToolResult{
Meta: mcp.Meta{metaPatternsKey: patterns, metaAlwaysKey: always},
}, nil
}
return h(ctx, req)
}
}
// RegisterPatternTool регистрирует инструмент с поддержкой forge-probe:
// помечает Tool.Meta флагом поддержки и оборачивает handler. Без флага хост
// не стал бы слать probe-вызов.
func RegisterPatternTool(s *mcp.Server, tool *mcp.Tool, fn PatternsFn, h mcp.ToolHandler) {
if tool.Meta == nil {
tool.Meta = mcp.Meta{}
}
tool.Meta[metaCapabilityKey] = true
s.AddTool(tool, WrapProbe(h, fn))
}
// IsProbe сообщает, является ли вызов probe-запросом паттернов.
func IsProbe(req *mcp.CallToolRequest) bool {
if req == nil || req.Params == nil {
return false
}
v, ok := req.Params.GetMeta()[metaProbeKey]
if !ok {
return false
}
b, _ := v.(bool)
return b
}
+19
View File
@@ -0,0 +1,19 @@
package toolkit
import "github.com/modelcontextprotocol/go-sdk/mcp"
// Text собирает успешный текстовый результат тула.
func Text(text string) *mcp.CallToolResult {
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: text}},
}
}
// Error собирает тул-уровневую ошибку (IsError=true → модель видит её для
// самокоррекции, а не падает на транспорте).
func Error(msg string) *mcp.CallToolResult {
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: msg}},
IsError: true,
}
}
+75
View File
@@ -0,0 +1,75 @@
package toolkit
import (
"context"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestTextAndError(t *testing.T) {
txt := Text("hello")
if txt.IsError {
t.Error("Text must not be an error")
}
if len(txt.Content) != 1 {
t.Fatalf("content = %v", txt.Content)
}
errRes := Error("boom")
if !errRes.IsError {
t.Error("Error must set IsError")
}
}
func TestIsProbe(t *testing.T) {
probe := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{
Meta: mcp.Meta{metaProbeKey: true},
}}
if !IsProbe(probe) {
t.Error("IsProbe = false, want true")
}
if IsProbe(nil) {
t.Error("nil request must not be probe")
}
if IsProbe(&mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{}}) {
t.Error("no meta must not be probe")
}
}
func TestWrapProbeInterceptsAndDelegates(t *testing.T) {
handlerCalled := false
h := func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
handlerCalled = true
return Text("real"), nil
}
fn := func(args map[string]any) ([]string, []string) {
return []string{"run:cat *"}, []string{"cat *"}
}
wrapped := WrapProbe(h, fn)
// Probe: действие не выполняется, возвращаются паттерны в _meta.
probe := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{
Meta: mcp.Meta{metaProbeKey: true},
Arguments: []byte(`{"command":"cat /etc/hosts"}`),
}}
res, err := wrapped(context.Background(), probe)
if err != nil {
t.Fatalf("probe: %v", err)
}
if handlerCalled {
t.Error("handler must not run on probe")
}
meta := res.GetMeta()
if meta[metaPatternsKey] == nil || meta[metaAlwaysKey] == nil {
t.Errorf("probe meta = %v", meta)
}
// Обычный вызов: делегируется handler.
normal := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{}}
if _, err := wrapped(context.Background(), normal); err != nil {
t.Fatalf("normal: %v", err)
}
if !handlerCalled {
t.Error("handler must run on normal call")
}
}
+69
View File
@@ -0,0 +1,69 @@
package toolkit
// Schema строит JSON Schema 2020-12 для входных аргументов тула.
// properties обязана быть объектом, а не null: часть LLM-провайдеров
// отклоняет "properties": null как невалидную схему тула без аргументов.
func Schema(properties map[string]any, required []string) map[string]any {
if properties == nil {
properties = map[string]any{}
}
s := map[string]any{
"type": "object",
"properties": properties,
}
if len(required) > 0 {
s["required"] = required
}
return s
}
// StrProps описывает строковое свойство (опц. enum допустимых значений).
func StrProps(desc string, required bool, enum ...string) map[string]any {
s := map[string]any{"type": "string", "description": desc}
if len(enum) > 0 {
s["enum"] = enum
}
return s
}
// IntProps описывает целочисленное свойство.
func IntProps(desc string, required bool) map[string]any {
return map[string]any{"type": "integer", "description": desc}
}
// NumProps описывает числовое свойство.
func NumProps(desc string, required bool) map[string]any {
return map[string]any{"type": "number", "description": desc}
}
// BoolProps описывает булево свойство.
func BoolProps(desc string, required bool) map[string]any {
return map[string]any{"type": "boolean", "description": desc}
}
// ArrayStringProps описывает массив строк.
func ArrayStringProps(desc string, required bool) map[string]any {
return map[string]any{
"type": "array",
"description": desc,
"items": map[string]any{"type": "string"},
}
}
// ArrayNumberProps описывает массив чисел.
func ArrayNumberProps(desc string, required bool) map[string]any {
return map[string]any{
"type": "array",
"description": desc,
"items": map[string]any{"type": "number"},
}
}
// ObjectProps описывает объект со строковыми значениями (напр. headers).
func ObjectProps(desc string, required bool) map[string]any {
return map[string]any{
"type": "object",
"description": desc,
"additionalProperties": map[string]any{"type": "string"},
}
}
+43
View File
@@ -0,0 +1,43 @@
package toolkit
import "testing"
func TestSchemaNilPropertiesBecomesObject(t *testing.T) {
s := Schema(nil, nil)
props, ok := s["properties"].(map[string]any)
if !ok || props == nil {
t.Fatalf("properties = %#v, want non-nil object", s["properties"])
}
if _, has := s["required"]; has {
t.Error("required must be omitted when empty")
}
}
func TestSchemaRequired(t *testing.T) {
s := Schema(map[string]any{"a": StrProps("A", true)}, []string{"a"})
req, ok := s["required"].([]string)
if !ok || len(req) != 1 || req[0] != "a" {
t.Fatalf("required = %#v", s["required"])
}
}
func TestStrPropsEnum(t *testing.T) {
s := StrProps("mode", true, "a", "b")
enum, ok := s["enum"].([]string)
if !ok || len(enum) != 2 {
t.Fatalf("enum = %#v", s["enum"])
}
if StrProps("x", false)["enum"] != nil {
t.Error("no enum expected without values")
}
}
func TestObjectProps(t *testing.T) {
s := ObjectProps("headers", false)
if s["type"] != "object" {
t.Errorf("type = %v", s["type"])
}
if s["additionalProperties"] == nil {
t.Error("additionalProperties must be set")
}
}
+42
View File
@@ -0,0 +1,42 @@
package toolkit
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// version — версия MCP-сервера в handshake. Модули не версионируются
// отдельно (образ общий), поэтому фиксирована.
const version = "1.0.0"
// Health сообщает, запрошен ли `--health`, и, если да, печатает "ok".
// Вызывается в начале main ДО построения Manager: health должен быть дешёвым
// (без чтения конфига и подключений).
func Health() bool {
if len(os.Args) > 1 && os.Args[1] == "--health" {
fmt.Println("ok")
return true
}
return false
}
// Run поднимает stdio-цикл MCP-сервера: graceful shutdown по SIGINT/SIGTERM,
// NewServer(name), register, StdioTransport. Возвращает ошибку запуска —
// main решает, как её залогировать и выйти.
func Run(name string, register func(*mcp.Server)) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
s := mcp.NewServer(&mcp.Implementation{
Name: name,
Version: version,
}, &mcp.ServerOptions{})
register(s)
return s.Run(ctx, &mcp.StdioTransport{})
}
+27
View File
@@ -0,0 +1,27 @@
# template
Каркас MCP-сервера на `forge-toolkit`: конфиг, потокобезопасный `Manager`,
один инструмент и корректный lifecycle.
## Как пользоваться
1. Скопируйте каталог и переименуйте модуль в `go.mod`
(`example.com/forge-tool` → ваш путь).
2. Замените доменную логику в `internal/tools/tools.go`.
3. Соберите и проверьте:
```bash
go mod tidy
go build -o forge-tool .
./forge-tool --health # → ok
```
## Подключение
Любой MCP-клиент — как обычный stdio-сервер:
```json
{ "mcpServers": { "forge-tool": { "command": "/abs/path/forge-tool", "args": ["-config", "/abs/path/config.json"] } } }
```
Контракт и правила — [`../docs/ARCHITECTURE.md`](../docs/ARCHITECTURE.md).
+3
View File
@@ -0,0 +1,3 @@
{
"greeting": "hello"
}
+21
View File
@@ -0,0 +1,21 @@
module example.com/forge-tool
go 1.27.0
require (
git.totmin.ru/en2zmax/forge-toolkit v0.1.0
github.com/modelcontextprotocol/go-sdk v1.7.0
)
require (
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/time v0.15.0 // indirect
)
replace git.totmin.ru/en2zmax/forge-toolkit => ..
+24
View File
@@ -0,0 +1,24 @@
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
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.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
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/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
+61
View File
@@ -0,0 +1,61 @@
// Package tools — доменный слой сервера: конфиг, Manager и инструменты.
// Замените содержимое на свою задачу; каркасные хелперы берите из toolkit.
package tools
import (
"context"
"encoding/json"
"os"
"strings"
"git.totmin.ru/en2zmax/forge-toolkit"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// Config — доменный конфиг сервера (пример). Замените поля на свои.
type Config struct {
Greeting string `json:"greeting"`
}
// LoadConfig читает config.json и разворачивает ${VAR}. Пустые обязательные
// поля лучше отвергать здесь (fail-closed), а не в обработчике.
func LoadConfig(path string) (*Config, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var cfg Config
if err := json.Unmarshal(toolkit.Expand(raw), &cfg); err != nil {
return nil, err
}
if strings.TrimSpace(cfg.Greeting) == "" {
cfg.Greeting = "hello"
}
return &cfg, nil
}
// Manager — доменное состояние сервера. Инструменты вызываются конкурентно,
// поэтому изменяемое состояние держите под sync.RWMutex.
type Manager struct {
cfg *Config
}
// NewManager создаёт Manager.
func NewManager(cfg *Config) *Manager { return &Manager{cfg: cfg} }
// Close освобождает ресурсы (соединения, файлы). В каркасе — no-op.
func (m *Manager) Close() {}
// RegisterAll регистрирует инструменты сервера.
func RegisterAll(s *mcp.Server, mgr *Manager) {
mcp.AddTool(s, &mcp.Tool{
Name: "greet",
Description: "Приветствие по имени. Без побочных эффектов.",
InputSchema: toolkit.Schema(map[string]any{
"name": toolkit.StrProps("имя", false),
}, nil),
}, func(_ context.Context, req *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, any, error) {
name := toolkit.GetString(toolkit.RequestArgs(req), "name", "world")
return toolkit.Text(mgr.cfg.Greeting + ", " + name + "!"), nil, nil
})
}
+42
View File
@@ -0,0 +1,42 @@
// Command forge-tool — каркас MCP-сервера на forge-toolkit.
//
// Скопируй каталог, переименуй модуль (go.mod) и замени доменную логику в
// internal/tools на свою. Точка входа — toolkit.Health (дешёвый --health) и
// toolkit.Run (stdio-цикл с graceful shutdown).
package main
import (
"flag"
"fmt"
"os"
"example.com/forge-tool/internal/tools"
"git.totmin.ru/en2zmax/forge-toolkit"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func main() {
if toolkit.Health() {
return
}
configPath := flag.String("config", "config.json", "путь к config.json")
flag.Parse()
cfg, err := tools.LoadConfig(*configPath)
if err != nil {
fmt.Fprintf(os.Stderr, "forge-tool: config: %v\n", err)
os.Exit(1)
}
mgr := tools.NewManager(cfg)
defer mgr.Close()
if err := toolkit.Run("forge-tool", func(s *mcp.Server) {
tools.RegisterAll(s, mgr)
}); err != nil {
fmt.Fprintf(os.Stderr, "forge-tool: %v\n", err)
os.Exit(1)
}
}
+324
View File
@@ -0,0 +1,324 @@
// Package validate — серверные (Go-native) валидаторы синтаксиса и детект
// типа файла по расширению. Все парсеры выполняются на MCP-сервере (ноль
// зависимостей от удалённого хоста). Вынесено из нескольких MCP-серверов,
// где код дублировался почти дословно.
package validate
import (
"bufio"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
"gopkg.in/yaml.v3"
)
// Result — итог проверки синтаксиса.
type Result struct {
Valid bool
FileType string
Errors []string
}
// FormatResult возвращает человекочитаемую сводку.
func (v *Result) FormatResult(path string) string {
if v.Valid {
return fmt.Sprintf("✓ Valid %s — %s", strings.ToUpper(v.FileType), path)
}
var b strings.Builder
fmt.Fprintf(&b, "✗ INVALID %s — %s\n", strings.ToUpper(v.FileType), path)
for _, e := range v.Errors {
b.WriteString(" " + e + "\n")
}
return strings.TrimRight(b.String(), "\n")
}
// Content валидирует сырой контент по типу файла. nil — тип не распознан
// (валидация невозможна).
func Content(content, fileType string) *Result {
switch fileType {
case "json":
return validateJSON(content)
case "yaml":
return validateYAML(content)
case "toml":
return validateTOML(content)
case "xml":
return validateXML(content)
case "ini":
return validateINI(content)
case "env":
return validateENV(content)
case "dockerfile":
return validateDockerfile(content)
default:
return nil
}
}
// --- JSON ---
func validateJSON(content string) *Result {
r := &Result{FileType: "json"}
var v interface{}
if err := json.Unmarshal([]byte(content), &v); err != nil {
r.Errors = append(r.Errors, err.Error())
return r
}
r.Valid = true
return r
}
// --- YAML ---
func validateYAML(content string) *Result {
r := &Result{FileType: "yaml"}
// Decode all documents (multi-doc YAML support)
dec := yaml.NewDecoder(strings.NewReader(content))
for {
var v interface{}
err := dec.Decode(&v)
if err == io.EOF {
break
}
if err != nil {
r.Errors = append(r.Errors, err.Error())
return r
}
}
r.Valid = true
return r
}
// --- TOML ---
func validateTOML(content string) *Result {
r := &Result{FileType: "toml"}
var v interface{}
if _, err := toml.Decode(content, &v); err != nil {
r.Errors = append(r.Errors, err.Error())
return r
}
r.Valid = true
return r
}
// --- XML ---
func validateXML(content string) *Result {
r := &Result{FileType: "xml"}
dec := xml.NewDecoder(strings.NewReader(content))
for {
_, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
r.Errors = append(r.Errors, err.Error())
return r
}
}
r.Valid = true
return r
}
// --- INI / .conf / .cfg ---
// Simple validator: checks section headers [section] and key=value pairs.
// Allows comments (# and ;) and blank lines.
func validateINI(content string) *Result {
r := &Result{FileType: "ini"}
scanner := bufio.NewScanner(strings.NewReader(content))
lineNum := 0
for scanner.Scan() {
lineNum++
line := strings.TrimSpace(scanner.Text())
// Blank or comment
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
continue
}
// Section header
if strings.HasPrefix(line, "[") {
if !strings.HasSuffix(line, "]") {
r.Errors = append(r.Errors, fmt.Sprintf("line %d: unclosed section header: %s", lineNum, line))
}
continue
}
// Key=value (allow key = value, key: value)
if strings.ContainsAny(line, "=:") {
continue
}
r.Errors = append(r.Errors, fmt.Sprintf("line %d: invalid syntax: %s", lineNum, line))
}
r.Valid = len(r.Errors) == 0
return r
}
// --- .env / dotenv ---
// Validates KEY=VALUE format. Allows comments (#) and blank lines.
// Keys must start with a letter or underscore.
func validateENV(content string) *Result {
r := &Result{FileType: "env"}
scanner := bufio.NewScanner(strings.NewReader(content))
lineNum := 0
for scanner.Scan() {
lineNum++
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
// Must contain = and key must start with letter/underscore
eqIdx := strings.Index(line, "=")
if eqIdx <= 0 {
r.Errors = append(r.Errors, fmt.Sprintf("line %d: missing KEY=VALUE format: %s", lineNum, line))
continue
}
key := line[:eqIdx]
key = strings.TrimSpace(key)
// Remove "export " prefix if present
key = strings.TrimPrefix(key, "export ")
key = strings.TrimSpace(key)
if key == "" {
r.Errors = append(r.Errors, fmt.Sprintf("line %d: empty key", lineNum))
continue
}
firstChar := key[0]
isLetter := firstChar >= 'A' && firstChar <= 'Z' || firstChar >= 'a' && firstChar <= 'z'
if !isLetter && firstChar != '_' {
r.Errors = append(r.Errors, fmt.Sprintf("line %d: key must start with letter or underscore: %s", lineNum, key))
}
}
r.Valid = len(r.Errors) == 0
return r
}
// --- Dockerfile ---
// Validates that each non-comment, non-continuation line starts with a known instruction.
var dockerfileInstructions = map[string]bool{
"FROM": true, "RUN": true, "CMD": true, "LABEL": true,
"EXPOSE": true, "ENV": true, "ADD": true, "COPY": true,
"ENTRYPOINT": true, "VOLUME": true, "USER": true, "WORKDIR": true,
"ARG": true, "ONBUILD": true, "STOPSIGNAL": true, "HEALTHCHECK": true,
"SHELL": true, "MAINTAINER": true,
}
func validateDockerfile(content string) *Result {
r := &Result{FileType: "dockerfile"}
scanner := bufio.NewScanner(strings.NewReader(content))
lineNum := 0
continuation := false
for scanner.Scan() {
lineNum++
line := scanner.Text()
trimmed := strings.TrimSpace(line)
// Handle line continuation from previous line
if continuation {
continuation = strings.HasSuffix(trimmed, "\\")
continue
}
// Skip blank lines and comments
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
// Check if line continues
continuation = strings.HasSuffix(trimmed, "\\")
// Extract instruction (first word)
parts := strings.Fields(trimmed)
if len(parts) == 0 {
continue
}
instruction := strings.ToUpper(parts[0])
// Handle parser directives (# syntax=..., # escape=...)
if strings.HasPrefix(instruction, "#") {
continue
}
if !dockerfileInstructions[instruction] {
r.Errors = append(r.Errors, fmt.Sprintf("line %d: unknown instruction: %s", lineNum, parts[0]))
}
}
// Check that FROM is present
hasFrom := false
scanner2 := bufio.NewScanner(strings.NewReader(content))
for scanner2.Scan() {
line := strings.TrimSpace(scanner2.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.Fields(line)
if len(parts) > 0 && strings.ToUpper(parts[0]) == "FROM" {
hasFrom = true
break
}
}
if !hasFrom && strings.TrimSpace(content) != "" {
r.Errors = append(r.Errors, "missing FROM instruction")
}
r.Valid = len(r.Errors) == 0
return r
}
// fileTypePatterns — сопоставление lowercase basename с типом файла.
var fileTypePatterns = []struct {
pattern string // matched against lowercase basename
fileType string
}{
{"*.json", "json"},
{"*.yaml", "yaml"},
{"*.yml", "yaml"},
{"*.toml", "toml"},
{"*.xml", "xml"},
{"*.xsl", "xml"},
{"*.xslt", "xml"},
{"*.svg", "xml"},
{"*.xhtml", "xml"},
{"*.plist", "xml"},
{"*.ini", "ini"},
{"*.cfg", "ini"},
{"*.conf", "ini"},
{"*.env", "env"},
{"dockerfile*", "dockerfile"},
{".env*", "env"},
}
// DetectFileType определяет тип файла по расширению или имени. Пусто — тип
// не распознан.
func DetectFileType(path string) string {
lower := strings.ToLower(path)
base := lower
if idx := strings.LastIndex(lower, "/"); idx >= 0 {
base = lower[idx+1:]
}
for _, p := range fileTypePatterns {
if matched, _ := filepath.Match(p.pattern, base); matched {
return p.fileType
}
}
return ""
}
+78
View File
@@ -0,0 +1,78 @@
package validate
import (
"strings"
"testing"
)
func TestContentValid(t *testing.T) {
cases := []struct {
name string
content string
fileType string
valid bool
}{
{"json ok", `{"a":1}`, "json", true},
{"json bad", `{`, "json", false},
{"yaml ok", "a: 1\nb: 2\n", "yaml", true},
{"yaml bad", "a: [1,\n", "yaml", false},
{"toml ok", "a = 1\n", "toml", true},
{"toml bad", "a = = 1\n", "toml", false},
{"xml ok", "<a><b/></a>", "xml", true},
{"xml bad", "<a><b></a>", "xml", false},
{"ini ok", "[s]\nk = v\n", "ini", true},
{"ini bad", "no separator line\n", "ini", false},
{"env ok", "FOO=bar\nexport BAZ=1\n", "env", true},
{"env bad", "1BAD=x\n", "env", false},
{"dockerfile ok", "FROM alpine\nRUN echo hi\n", "dockerfile", true},
{"dockerfile bad", "FROM alpine\nBOGUS x\n", "dockerfile", false},
{"unknown type", "whatever", "nope", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
r := Content(tc.content, tc.fileType)
if tc.fileType == "nope" {
if r != nil {
t.Fatalf("unknown type must return nil, got %+v", r)
}
return
}
if r == nil {
t.Fatal("nil result")
}
if r.Valid != tc.valid {
t.Errorf("Valid = %v, want %v (errors=%v)", r.Valid, tc.valid, r.Errors)
}
})
}
}
func TestDetectFileType(t *testing.T) {
cases := map[string]string{
"a.json": "json",
"dir/b.yaml": "yaml",
"c.YML": "yaml",
"Dockerfile": "dockerfile",
"path/to/Dockerfile": "dockerfile",
".env": "env",
".env.local": "env",
"conf/app.conf": "ini",
"x.txt": "",
}
for in, want := range cases {
if got := DetectFileType(in); got != want {
t.Errorf("DetectFileType(%q) = %q, want %q", in, got, want)
}
}
}
func TestFormatResult(t *testing.T) {
ok := &Result{Valid: true, FileType: "json"}
if got := ok.FormatResult("/a.json"); !strings.HasPrefix(got, "✓") {
t.Errorf("valid format = %q", got)
}
bad := &Result{FileType: "json", Errors: []string{"boom"}}
if got := bad.FormatResult("/a.json"); !strings.HasPrefix(got, "✗") {
t.Errorf("invalid format = %q", got)
}
}