Compare commits

..
14 Commits
Author SHA1 Message Date
gronod 07949c1a63 fix(issue): satisfy embedlit lint in check_blocked
check-and-test / check-and-test (pull_request) Successful in 4m23s
release-nightly / release-image (push) Successful in 3m8s
Use the same ListOptions local as the other list helpers instead of
embedding gitea_sdk.ListOptions in the composite literal.
2026-09-16 08:20:35 +00:00
gronod 3e093c10b9 feat(issue): support cross-repo dependencies and check_blocked
check-and-test / check-and-test (pull_request) Failing after 2m25s
Send blocked_owner/blocked_repo and blocking_owner/blocking_repo in the
IssueMeta body so Gitea can resolve cross-repository links. Default those
fields to the path issue's owner/repo.

Add issue_read method check_blocked to summarize open blockers, and
document that dependency endpoints 404 when the repo has issue
dependencies disabled.
2026-09-16 08:03:23 +00:00
gronod 10f5a345d8 fix(issue): include owner and repo in dependency request bodies
check-and-test / check-and-test (pull_request) Successful in 2m23s
release-nightly / release-image (push) Successful in 2m58s
Gitea resolves the IssueMeta body against owner+repo, not only the
URL. The SDK type only has Index, so block/unblock/add/remove
dependency calls looked up a repo named "". Send the path owner/repo
in the JSON body via DoJSON.

Assisted-by: Devin:SWE-2 Medium
2026-09-15 16:20:56 +01:00
gronod 554b7490e2 Merge pull request 'feat(issue): add issue blocking methods' (#2) from feat/issue-blocks into main
release-nightly / release-image (push) Successful in 2m28s
Reviewed-on: #2
2026-09-15 15:39:53 +01:00
gronod 9bfd55f97d fix(ci): login to registry with PAT secret
release-nightly / release-image (push) Successful in 2m32s
The actions task token is rejected by the container registry
(unauthorized at /v2/); use the REGISTRY_TOKEN repo secret instead.

Assisted-by: Devin:SWE-2-Medium
2026-09-15 15:19:21 +01:00
gronod 026f40bc15 feat(issue): add dependency methods to issue tools
check-and-test / check-and-test (pull_request) Successful in 2m21s
Expose Gitea /issues/{i}/dependencies endpoints: list_dependencies on
issue_read and add_dependency/remove_dependency on issue_write via the
blocking_issue param.

Assisted-by: Devin:SWE-2 Max
2026-09-15 14:48:10 +01:00
gronod 4f7a191b67 feat(issue): add block/unblock methods to issue tools
check-and-test / check-and-test (pull_request) Successful in 2m46s
Expose Gitea /issues/{i}/blocks endpoints: list_blocks on issue_read and
block_issue/unblock_issue on issue_write, with pagination params on
issue_read.

Assisted-by: Devin:SWE-2 Max
2026-09-15 14:46:47 +01:00
gronod 290ad8da5d chore(release): publish to self-hosted gitea instance
check-and-test / check-and-test (pull_request) Successful in 4m50s
release-nightly / release-image (push) Failing after 1m1s
Repoint image pushes to git.i3omb.com/gronod/gitea-mcp-server using
GITHUB_TOKEN auth, drop the Cloudflare R2 mirror, and update the docs
and OCI source label to match.

Assisted-by: Devin:SWE-2 High
2026-09-15 13:58:13 +01:00
Renovate Bot 87fd1a7fa2 chore(deps): update module golang.org/x/vuln to v1.8.0 (#267)
Co-authored-by: Renovate Bot <renovate-bot@gitea.com>
2026-09-14 12:06:52 +00:00
Renovate Bot e31f3c3764 chore(deps): update dependencies (#265)
Co-authored-by: Renovate Bot <renovate-bot@gitea.com>
2026-09-08 01:32:47 +00:00
Renovate Bot 0157291800 fix(deps): update module golang.org/x/crypto to v0.56.0 [security] (#262)
This PR contains the following updates:

| Package | Change | [Age](https://docs.renovatebot.com/merge-confidence/) | [Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
| [golang.org/x/crypto](https://pkg.go.dev/golang.org/x/crypto) | [`v0.55.0` → `v0.56.0`](https://cs.opensource.google/go/x/crypto/+/refs/tags/v0.55.0...refs/tags/v0.56.0) | ![age](https://developer.mend.io/api/mc/badges/age/go/golang.org%2fx%2fcrypto/v0.56.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/go/golang.org%2fx%2fcrypto/v0.55.0/v0.56.0?slim=true) |

---

### Prevent DoS on deadlocked undecided channel in golang.org/x/crypto/ssh
[CVE-2026-78662](https://nvd.nist.gov/vuln/detail/CVE-2026-78662) / [GO-2026-6354](https://pkg.go.dev/vuln/GO-2026-6354)

<details>
<summary>More information</summary>

#### Details
Previously, a channel registered in the mux's chanList is not usable until it is established. A malicious peer was able flood the channel's incomingRequests, deadlocking the entire connection.

Now, we add an atomic established state, set when a channel becomes usable. Until such a time, handlePacket drops every packet other than the open confirmation/failure, without blocking and without tearing down the connection.

#### Severity
Unknown

#### References
- [https://go.dev/issue/81316](https://go.dev/issue/81316)
- [https://go.dev/cl/826504](https://go.dev/cl/826504)
- [https://groups.google.com/g/golang-announce/c/1y3fb2np35U](https://groups.google.com/g/golang-announce/c/1y3fb2np35U)

This data is provided by [OSV](https://osv.dev/vulnerability/GO-2026-6354) and the [Go Vulnerability Database](https://github.com/golang/vulndb) ([CC-BY 4.0](https://github.com/golang/vulndb#license)).
</details>

---

### Prevent DoS on deadlocked established channel in golang.org/x/crypto/ssh
[CVE-2026-56855](https://nvd.nist.gov/vuln/detail/CVE-2026-56855) / [GO-2026-6355](https://pkg.go.dev/vuln/GO-2026-6355)

<details>
<summary>More information</summary>

#### Details
Previously, after a channel has been established, a malicious peer could send crafted messages that would deadlock the entire connection.

Now, we handle all RFC 4254 channel messages; global requests are handled explicitly. Then, treat all other messages as a protocol error and tear the connection down instead of buffering and blocking.

#### Severity
Unknown

#### References
- [https://go.dev/issue/81317](https://go.dev/issue/81317)
- [https://go.dev/cl/826524](https://go.dev/cl/826524)
- [https://groups.google.com/g/golang-announce/c/1y3fb2np35U](https://groups.google.com/g/golang-announce/c/1y3fb2np35U)

This data is provided by [OSV](https://osv.dev/vulnerability/GO-2026-6355) and the [Go Vulnerability Database](https://github.com/golang/vulndb) ([CC-BY 4.0](https://github.com/golang/vulndb#license)).
</details>

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4xOTEuMiIsInVwZGF0ZWRJblZlciI6IjQzLjE5MS4yIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/262
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Renovate Bot <renovate-bot@gitea.com>
2026-09-03 06:41:19 +00:00
Lunny Xiao bfe0d4c9b0 feat(docker): add /healthz endpoint and -healthcheck flag (#254)
Adds a Docker healthcheck and the small HTTP/CLI plumbing it needs.

- Expose `GET /healthz` on the HTTP-mode server.
- Add `-healthcheck` to dial `http://127.0.0.1:<port>/healthz` and exit with status.
- Add a Dockerfile `HEALTHCHECK` instruction using `-healthcheck`.
- Document HTTP-mode usage and stdio override guidance.

Closes https://gitea.com/gitea/gitea-mcp/issues/146

Assisted by Codet.

Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/254
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
2026-08-26 03:00:05 +00:00
Lunny Xiao 04931d48a3 feat(repo): add rename_branch tool (#245)
Adds a native `rename_branch` write tool so MCP clients can rename branches without emulating it via create + delete.

Changes:
- Add `rename_branch` to the repository branch tools with `owner`, `repo`, `branch`, and `new_name` parameters.
- Call the Gitea SDK's `RenameRepoBranch` operation and propagate API errors.
- Add handler/registration tests and README tool table entries.

Closes https://gitea.com/gitea/gitea-mcp/issues/236

Assisted by Codet

Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/245
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
2026-08-24 23:36:48 +00:00
Renovate Botandsilverwind e2052d903f chore(deps): update dependencies (#243)
This PR contains the following updates:

| Package | Type | Update | Change | [Age](https://docs.renovatebot.com/merge-confidence/) | [Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|---|---|
| [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) ([changelog](https://github.com/docker/setup-buildx-action/compare/bb05f3f5519dd87d3ba754cc423b652a5edd6d2c..37fe631027851001ddb9b187196cc803df7f5f0e)) | action | digest | `bb05f3f` → `37fe631` |  |  |
| [go](https://go.dev/) ([source](https://github.com/golang/go)) | toolchain | minor | `1.26.6` → `1.27.0` | ![age](https://developer.mend.io/api/mc/badges/age/golang-version/go/1.27.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/golang-version/go/1.26.6/1.27.0?slim=true) |
| golang.org/x/vuln |  | minor | `v1.6.0` → `v1.7.0` | ![age](https://developer.mend.io/api/mc/badges/age/go/golang.org%2fx%2fvuln/v1.7.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/go/golang.org%2fx%2fvuln/v1.6.0/v1.7.0?slim=true) |

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - Between 12:00 AM and 03:59 AM, only on Monday (`* 0-3 * * 1`)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4xOTEuMiIsInVwZGF0ZWRJblZlciI6IjQzLjE5MS4yIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

---------

Co-authored-by: silverwind <me@silverwind.io>
Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/243
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Renovate Bot <renovate-bot@gitea.com>
2026-08-24 17:21:20 +00:00
46 changed files with 898 additions and 1534 deletions
+9 -9
View File
@@ -10,8 +10,8 @@ jobs:
release-image: release-image:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
DOCKER_ORG: gitea REGISTRY: git.i3omb.com
DOCKER_LATEST: nightly IMAGE_NAME: gronod/gitea-mcp-server
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
@@ -19,21 +19,21 @@ jobs:
fetch-depth: 0 # all history for all branches and tags fetch-depth: 0 # all history for all branches and tags
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4 uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4
- name: Set up Docker BuildX - name: Set up Docker BuildX
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4 uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
- name: Login to DockerHub - name: Login to container registry
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
with: with:
username: ${{ secrets.DOCKER_USER }} registry: ${{ env.REGISTRY }}
password: ${{ secrets.DOCKER_TOKEN }} username: gronod
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Get Meta - name: Get Meta
id: meta id: meta
run: | run: |
echo REPO_NAME=$(echo ${GITHUB_REPOSITORY} | awk -F"/" '{print $2}') >> $GITHUB_OUTPUT
echo REPO_VERSION=$(git describe --tags --always | sed 's/-/+/' | sed 's/^v//') >> $GITHUB_OUTPUT echo REPO_VERSION=$(git describe --tags --always | sed 's/-/+/' | sed 's/^v//') >> $GITHUB_OUTPUT
- name: Build and push - name: Build and push
@@ -46,6 +46,6 @@ jobs:
linux/arm64 linux/arm64
push: true push: true
tags: | tags: |
${{ env.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}-server:${{ env.DOCKER_LATEST }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:nightly
build-args: | build-args: |
VERSION=${{ steps.meta.outputs.REPO_VERSION }} VERSION=${{ steps.meta.outputs.REPO_VERSION }}
+10 -35
View File
@@ -13,16 +13,6 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with: with:
fetch-depth: 0 fetch-depth: 0
# The R2 upload only runs after goreleaser has already published
# the Gitea release, so fail early instead if the secrets are
# missing.
- name: Check R2 configuration
run: sh scripts/upload-r2.sh --check-config
env:
R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }}
R2_BUCKET: ${{ secrets.R2_BUCKET }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
- name: Set up Go - name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7 uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
with: with:
@@ -35,27 +25,12 @@ jobs:
env: env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GORELEASER_FORCE_TOKEN: "gitea" GORELEASER_FORCE_TOKEN: "gitea"
# goreleaser `publishers:` is a Pro-only feature, so the release
# artifacts are mirrored to Cloudflare R2 here instead.
- name: Upload binaries to Cloudflare R2
env:
R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }}
R2_BUCKET: ${{ secrets.R2_BUCKET }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
VERSION: ${{ github.ref_name }}
run: |
for f in dist/*.tar.gz dist/*.zip dist/checksums.txt; do
[ -f "$f" ] || continue
echo "uploading $f"
sh scripts/upload-r2.sh "$f" "gitea-mcp/${VERSION#v}/$(basename "$f")"
done
release-image: release-image:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
DOCKER_ORG: gitea REGISTRY: git.i3omb.com
DOCKER_LATEST: latest IMAGE_NAME: gronod/gitea-mcp-server
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
@@ -63,21 +38,21 @@ jobs:
fetch-depth: 0 # all history for all branches and tags fetch-depth: 0 # all history for all branches and tags
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4 uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4
- name: Set up Docker BuildX - name: Set up Docker BuildX
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4 uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
- name: Login to DockerHub - name: Login to container registry
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
with: with:
username: ${{ secrets.DOCKER_USER }} registry: ${{ env.REGISTRY }}
password: ${{ secrets.DOCKER_TOKEN }} username: gronod
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Get Meta - name: Get Meta
id: meta id: meta
run: | run: |
echo REPO_NAME=$(echo ${GITHUB_REPOSITORY} | awk -F"/" '{print $2}') >> $GITHUB_OUTPUT
echo REPO_VERSION=${GITHUB_REF_NAME#v} >> $GITHUB_OUTPUT echo REPO_VERSION=${GITHUB_REF_NAME#v} >> $GITHUB_OUTPUT
- name: Build and push - name: Build and push
@@ -92,5 +67,5 @@ jobs:
build-args: | build-args: |
VERSION=${{ steps.meta.outputs.REPO_VERSION }} VERSION=${{ steps.meta.outputs.REPO_VERSION }}
tags: | tags: |
${{ env.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}-server:${{ steps.meta.outputs.REPO_VERSION }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.REPO_VERSION }}
${{ env.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}-server:${{ env.DOCKER_LATEST }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
+3 -2
View File
@@ -74,7 +74,7 @@ linters:
arguments: arguments:
- [] # AllowList - do not remove as args for the rule are positional and won't work without lists first - [] # AllowList - do not remove as args for the rule are positional and won't work without lists first
- [] # DenyList - [] # DenyList
- - skip-package-name-checks: true - - skip-initialism-name-checks: true
staticcheck: staticcheck:
checks: checks:
- all - all
@@ -110,7 +110,8 @@ formatters:
- blank - blank
- default - default
gofumpt: gofumpt:
extra-rules: true extra:
group-params: true
exclusions: exclusions:
generated: lax generated: lax
run: run:
+2 -2
View File
@@ -71,6 +71,6 @@ release:
Released by [GoReleaser](https://github.com/goreleaser/goreleaser). Released by [GoReleaser](https://github.com/goreleaser/goreleaser).
gitea_urls: gitea_urls:
api: https://gitea.com/api/v1 api: https://git.i3omb.com/api/v1
download: https://gitea.com download: https://git.i3omb.com
force_token: gitea force_token: gitea
+1 -1
View File
@@ -4,7 +4,7 @@ This project includes PowerShell and batch scripts to build the gitea-mcp applic
## Prerequisites ## Prerequisites
- Go 1.26 or later - Go 1.27 or later
- Git (for version information) - Git (for version information)
- PowerShell 5.1 or later (included with Windows 10/11) - PowerShell 5.1 or later (included with Windows 10/11)
+6 -3
View File
@@ -1,7 +1,7 @@
# syntax=docker/dockerfile:1.26 # syntax=docker/dockerfile:1.27
# Build stage # Build stage
FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS builder FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS builder
ARG VERSION=dev ARG VERSION=dev
ARG TARGETOS ARG TARGETOS
@@ -30,6 +30,9 @@ COPY --from=builder --chown=nonroot:nonroot /app/gitea-mcp .
USER nonroot:nonroot USER nonroot:nonroot
LABEL org.opencontainers.image.version="${VERSION}" LABEL org.opencontainers.image.version="${VERSION}"
LABEL org.opencontainers.image.source="https://gitea.com/gitea/gitea-mcp" LABEL org.opencontainers.image.source="https://git.i3omb.com/gronod/gitea-mcp"
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD ["/app/gitea-mcp", "-healthcheck"] || exit 1
CMD ["/app/gitea-mcp"] CMD ["/app/gitea-mcp"]
+2 -2
View File
@@ -3,8 +3,8 @@ EXECUTABLE := gitea-mcp
VERSION ?= $(shell git describe --tags --always | sed 's/-/+/' | sed 's/^v//') VERSION ?= $(shell git describe --tags --always | sed 's/-/+/' | sed 's/^v//')
LDFLAGS := -X "main.Version=$(VERSION)" LDFLAGS := -X "main.Version=$(VERSION)"
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.12.2 # renovate: datasource=go GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13.2 # renovate: datasource=go
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v1.6.0 # renovate: datasource=go GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v1.8.0 # renovate: datasource=go
GOTEST_FLAGS ?= -race -timeout 20m GOTEST_FLAGS ?= -race -timeout 20m
+10 -9
View File
@@ -4,14 +4,14 @@
**Gitea MCP Server** connects a [Gitea](https://about.gitea.com) instance to [Model Context Protocol](https://modelcontextprotocol.io) clients, so repositories, issues, pull requests and more can be browsed and managed from an MCP-compatible chat interface. **Gitea MCP Server** connects a [Gitea](https://about.gitea.com) instance to [Model Context Protocol](https://modelcontextprotocol.io) clients, so repositories, issues, pull requests and more can be browsed and managed from an MCP-compatible chat interface.
[![Install with Docker in VS Code](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [![Install with Docker in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders) [![Install with Docker in VS Code](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22git.i3omb.com/gronod/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [![Install with Docker in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22git.i3omb.com/gronod/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
## Installation ## Installation
Download a binary from the [releases page](https://gitea.com/gitea/gitea-mcp/releases) and put it in your `PATH`, use the `docker.gitea.com/gitea-mcp-server` image, or build from source into `$GOPATH/bin` with `make` and Go 1.26 or later: Download a binary from the [releases page](https://git.i3omb.com/gronod/gitea-mcp/releases) and put it in your `PATH`, use the `git.i3omb.com/gronod/gitea-mcp-server` image, or build from source into `$GOPATH/bin` with `make` and Go 1.27 or later:
```bash ```bash
git clone https://gitea.com/gitea/gitea-mcp.git git clone https://git.i3omb.com/gronod/gitea-mcp.git
cd gitea-mcp cd gitea-mcp
make install make install
``` ```
@@ -26,6 +26,8 @@ The server supports MCP up to `2026-07-28` and negotiates down to the client's v
HTTP is always stateless: `/mcp` accepts POST only, without `Mcp-Session-Id`, standalone SSE or `Last-Event-ID` resumability. Origins are validated, and reverse proxies must forward `Mcp-Protocol-Version`, `Mcp-Method` and `Mcp-Name` unchanged. `Authorization: Bearer <token>` and `Authorization: token <token>` pass a Gitea credential per request, which is credential passthrough rather than MCP OAuth. HTTP is always stateless: `/mcp` accepts POST only, without `Mcp-Session-Id`, standalone SSE or `Last-Event-ID` resumability. Origins are validated, and reverse proxies must forward `Mcp-Protocol-Version`, `Mcp-Method` and `Mcp-Name` unchanged. `Authorization: Bearer <token>` and `Authorization: token <token>` pass a Gitea credential per request, which is credential passthrough rather than MCP OAuth.
HTTP mode also serves `/healthz`, which returns `200 OK` when the server is up. The Docker image's built-in `HEALTHCHECK` runs `gitea-mcp -healthcheck`, which dials `http://127.0.0.1:<port>/healthz` using the same `-p`/`-port` value (or `8080` by default) and exits `0` on success or `1` on failure. Stdio deployments do not serve `/healthz`, so override or disable the image's `HEALTHCHECK` when running in stdio mode.
### Claude Code ### Claude Code
Runs the server through `go run` and requires [Go](https://go.dev): Runs the server through `go run` and requires [Go](https://go.dev):
@@ -55,7 +57,7 @@ Use the install buttons at the top of this README, or add the block below to you
"servers": { "servers": {
"gitea-mcp": { "gitea-mcp": {
"command": "docker", "command": "docker",
"args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "docker.gitea.com/gitea-mcp-server"], "args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "git.i3omb.com/gronod/gitea-mcp-server"],
"env": { "env": {
"GITEA_ACCESS_TOKEN": "${input:gitea_token}" "GITEA_ACCESS_TOKEN": "${input:gitea_token}"
} }
@@ -91,7 +93,7 @@ Add the following to `~/.vibe/config.toml`:
name = "gitea" name = "gitea"
transport = "stdio" transport = "stdio"
command = "docker" command = "docker"
args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "docker.gitea.com/gitea-mcp-server"] args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "git.i3omb.com/gronod/gitea-mcp-server"]
[mcp_servers.env] [mcp_servers.env]
GITEA_ACCESS_TOKEN = "TOKEN" GITEA_ACCESS_TOKEN = "TOKEN"
@@ -156,12 +158,10 @@ Once configured, try `list all my repositories` in the chat box.
| timetracking_write | timetracking | Write | Write time tracking: stopwatches and entries | | timetracking_write | timetracking | Write | Write time tracking: stopwatches and entries |
| package_read | packages | Read | Read package registry: list packages, list versions, or get a version | | package_read | packages | Read | Read package registry: list packages, list versions, or get a version |
| package_write | packages | Write | Delete a package version (irreversible) | | package_write | packages | Write | Delete a package version (irreversible) |
| project_read | project | Read | Read projects: list projects, get a project, list columns, get a column, or list issues in a column |
| project_write | project | Write | Write projects: create, update, or delete projects and columns; reorder columns; add, remove, or move issues |
| list_issues | issue | Read | List repository issues | | list_issues | issue | Read | List repository issues |
| attachment_read | issue | Read | Read issue/comment attachments: list metadata, get metadata, or download content | | attachment_read | issue | Read | Read issue/comment attachments: list metadata, get metadata, or download content |
| issue_read | issue | Read | Read issue: details, comments, or labels | | issue_read | issue | Read | Read issue: details, comments, labels, or dependency/blocking links |
| issue_write | issue | Write | Write issues: create, update, manage comments and labels | | issue_write | issue | Write | Write issues: create, update, manage comments, labels, and dependency/blocking links |
| list_pull_requests | pull_request | Read | List repository pull requests | | list_pull_requests | pull_request | Read | List repository pull requests |
| pull_request_read | pull_request | Read | Read pull request: details, diff, files, status, reviews, review comments | | pull_request_read | pull_request | Read | Read pull request: details, diff, files, status, reviews, review comments |
| pull_request_write | pull_request | Write | Write pull requests: create, update, close, reopen, merge, update branch, manage reviewers | | pull_request_write | pull_request | Write | Write pull requests: create, update, close, reopen, merge, update branch, manage reviewers |
@@ -182,6 +182,7 @@ Once configured, try `list all my repositories` in the chat box.
| create_branch | branch | Write | Create a new branch | | create_branch | branch | Write | Create a new branch |
| delete_branch | branch | Write | Delete a branch | | delete_branch | branch | Write | Delete a branch |
| list_branches | branch | Read | List repository branches | | list_branches | branch | Read | List repository branches |
| rename_branch | branch | Write | Rename a branch |
| create_tag | tag | Write | Create a tag | | create_tag | tag | Write | Create a tag |
| delete_tag | tag | Write | Delete a tag | | delete_tag | tag | Write | Delete a tag |
| get_tag | tag | Read | Get tag details | | get_tag | tag | Read | Get tag details |
+10 -9
View File
@@ -4,14 +4,14 @@
**Gitea MCP 服务器** 将 [Gitea](https://about.gitea.com) 实例接入 [Model Context Protocol](https://modelcontextprotocol.io) 客户端,让仓库、问题、拉取请求等都能在兼容 MCP 的聊天界面中浏览和管理。 **Gitea MCP 服务器** 将 [Gitea](https://about.gitea.com) 实例接入 [Model Context Protocol](https://modelcontextprotocol.io) 客户端,让仓库、问题、拉取请求等都能在兼容 MCP 的聊天界面中浏览和管理。
[![在 VS Code 中使用 Docker 安装](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [![在 VS Code Insiders 中使用 Docker 安装](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders) [![在 VS Code 中使用 Docker 安装](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22git.i3omb.com/gronod/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [![在 VS Code Insiders 中使用 Docker 安装](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22git.i3omb.com/gronod/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
## 安装 ## 安装
可从 [发布页面](https://gitea.com/gitea/gitea-mcp/releases) 下载二进制文件并放入 `PATH`,或使用 `docker.gitea.com/gitea-mcp-server` 镜像,也可用 `make` 和 Go 1.26 及以上从源码构建到 `$GOPATH/bin`: 可从 [发布页面](https://git.i3omb.com/gronod/gitea-mcp/releases) 下载二进制文件并放入 `PATH`,或使用 `git.i3omb.com/gronod/gitea-mcp-server` 镜像,也可用 `make` 和 Go 1.27 及以上从源码构建到 `$GOPATH/bin`:
```bash ```bash
git clone https://gitea.com/gitea/gitea-mcp.git git clone https://git.i3omb.com/gronod/gitea-mcp.git
cd gitea-mcp cd gitea-mcp
make install make install
``` ```
@@ -26,6 +26,8 @@ Gitea 主机和访问令牌可通过命令行参数或环境变量提供,命
HTTP 传输固定为无状态:`/mcp` 仅接受 POST,没有 `Mcp-Session-Id`、独立 SSE 和 `Last-Event-ID` 断点续传。服务器会验证来源,反向代理必须原样转发 `Mcp-Protocol-Version`、`Mcp-Method` 和 `Mcp-Name`。`Authorization: Bearer <令牌>` 和 `Authorization: token <令牌>` 会在每个请求中传递 Gitea 凭据,这是凭据透传,而不是 MCP OAuth。 HTTP 传输固定为无状态:`/mcp` 仅接受 POST,没有 `Mcp-Session-Id`、独立 SSE 和 `Last-Event-ID` 断点续传。服务器会验证来源,反向代理必须原样转发 `Mcp-Protocol-Version`、`Mcp-Method` 和 `Mcp-Name`。`Authorization: Bearer <令牌>` 和 `Authorization: token <令牌>` 会在每个请求中传递 Gitea 凭据,这是凭据透传,而不是 MCP OAuth。
HTTP 模式还提供 `/healthz` 端点,服务器正常运行时返回 `200 OK`。Docker 镜像内置的 `HEALTHCHECK` 会运行 `gitea-mcp -healthcheck`,它使用与 `-p`/`-port` 相同的端口(默认 `8080`)请求 `http://127.0.0.1:<端口>/healthz`,成功时退出码为 `0`,失败时为 `1`。stdio 部署不提供 `/healthz`,因此在 stdio 模式下运行时应覆盖或禁用镜像自带的 `HEALTHCHECK`。
### Claude Code ### Claude Code
通过 `go run` 运行服务器,需要安装 [Go](https://go.dev): 通过 `go run` 运行服务器,需要安装 [Go](https://go.dev):
@@ -55,7 +57,7 @@ claude mcp add --transport stdio --scope user gitea \
"servers": { "servers": {
"gitea-mcp": { "gitea-mcp": {
"command": "docker", "command": "docker",
"args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "docker.gitea.com/gitea-mcp-server"], "args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "git.i3omb.com/gronod/gitea-mcp-server"],
"env": { "env": {
"GITEA_ACCESS_TOKEN": "${input:gitea_token}" "GITEA_ACCESS_TOKEN": "${input:gitea_token}"
} }
@@ -91,7 +93,7 @@ claude mcp add --transport stdio --scope user gitea \
name = "gitea" name = "gitea"
transport = "stdio" transport = "stdio"
command = "docker" command = "docker"
args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "docker.gitea.com/gitea-mcp-server"] args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "git.i3omb.com/gronod/gitea-mcp-server"]
[mcp_servers.env] [mcp_servers.env]
GITEA_ACCESS_TOKEN = "TOKEN" GITEA_ACCESS_TOKEN = "TOKEN"
@@ -156,12 +158,10 @@ Cursor 等客户端可使用 stdio 命令:
| timetracking_write | timetracking | 写入 | 写入时间跟踪:计时器和记录条目 | | timetracking_write | timetracking | 写入 | 写入时间跟踪:计时器和记录条目 |
| package_read | packages | 读取 | 读取软件包注册表:列出软件包、列出版本或获取某个版本 | | package_read | packages | 读取 | 读取软件包注册表:列出软件包、列出版本或获取某个版本 |
| package_write | packages | 写入 | 删除软件包版本(不可恢复) | | package_write | packages | 写入 | 删除软件包版本(不可恢复) |
| project_read | project | 读取 | 读取项目:列出项目、获取项目、列出列、获取列或列出列中的议题 |
| project_write | project | 写入 | 写入项目:创建、更新或删除项目与列;重新排序列;添加、移除或移动议题 |
| list_issues | issue | 读取 | 列出仓库问题 | | list_issues | issue | 读取 | 列出仓库问题 |
| attachment_read | issue | 读取 | 读取问题/评论附件:列出元数据、获取元数据或下载内容 | | attachment_read | issue | 读取 | 读取问题/评论附件:列出元数据、获取元数据或下载内容 |
| issue_read | issue | 读取 | 读取问题:详情、评论或标签 | | issue_read | issue | 读取 | 读取问题:详情、评论、标签或阻塞关系 |
| issue_write | issue | 写入 | 写入问题:创建、更新、管理评论和标签 | | issue_write | issue | 写入 | 写入问题:创建、更新、管理评论、标签和阻塞关系 |
| list_pull_requests | pull_request | 读取 | 列出仓库拉取请求 | | list_pull_requests | pull_request | 读取 | 列出仓库拉取请求 |
| pull_request_read | pull_request | 读取 | 读取拉取请求:详情、差异、变更文件、头部提交状态、审查、审查评论 | | pull_request_read | pull_request | 读取 | 读取拉取请求:详情、差异、变更文件、头部提交状态、审查、审查评论 |
| pull_request_write | pull_request | 写入 | 写入拉取请求:创建、更新、关闭、重新打开、合并、更新分支、管理审查者 | | pull_request_write | pull_request | 写入 | 写入拉取请求:创建、更新、关闭、重新打开、合并、更新分支、管理审查者 |
@@ -182,6 +182,7 @@ Cursor 等客户端可使用 stdio 命令:
| create_branch | branch | 写入 | 创建新分支 | | create_branch | branch | 写入 | 创建新分支 |
| delete_branch | branch | 写入 | 删除分支 | | delete_branch | branch | 写入 | 删除分支 |
| list_branches | branch | 读取 | 列出仓库分支 | | list_branches | branch | 读取 | 列出仓库分支 |
| rename_branch | branch | 写入 | 重命名分支 |
| create_tag | tag | 写入 | 创建标签 | | create_tag | tag | 写入 | 创建标签 |
| delete_tag | tag | 写入 | 删除标签 | | delete_tag | tag | 写入 | 删除标签 |
| get_tag | tag | 读取 | 获取标签详情 | | get_tag | tag | 读取 | 获取标签详情 |
+10 -9
View File
@@ -4,14 +4,14 @@
**Gitea MCP 伺服器** 將 [Gitea](https://about.gitea.com) 實例接入 [Model Context Protocol](https://modelcontextprotocol.io) 客戶端,讓倉庫、問題、拉取請求等都能在相容 MCP 的聊天介面中瀏覽與管理。 **Gitea MCP 伺服器** 將 [Gitea](https://about.gitea.com) 實例接入 [Model Context Protocol](https://modelcontextprotocol.io) 客戶端,讓倉庫、問題、拉取請求等都能在相容 MCP 的聊天介面中瀏覽與管理。
[![在 VS Code 中使用 Docker 安裝](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [![在 VS Code Insiders 中使用 Docker 安裝](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders) [![在 VS Code 中使用 Docker 安裝](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22git.i3omb.com/gronod/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [![在 VS Code Insiders 中使用 Docker 安裝](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22git.i3omb.com/gronod/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
## 安裝 ## 安裝
可從 [發布頁面](https://gitea.com/gitea/gitea-mcp/releases) 下載二進位檔並放入 `PATH`,或使用 `docker.gitea.com/gitea-mcp-server` 映像檔,也可用 `make` 與 Go 1.26 以上從原始碼建置到 `$GOPATH/bin`: 可從 [發布頁面](https://git.i3omb.com/gronod/gitea-mcp/releases) 下載二進位檔並放入 `PATH`,或使用 `git.i3omb.com/gronod/gitea-mcp-server` 映像檔,也可用 `make` 與 Go 1.27 以上從原始碼建置到 `$GOPATH/bin`:
```bash ```bash
git clone https://gitea.com/gitea/gitea-mcp.git git clone https://git.i3omb.com/gronod/gitea-mcp.git
cd gitea-mcp cd gitea-mcp
make install make install
``` ```
@@ -26,6 +26,8 @@ Gitea 主機與存取令牌可透過命令列參數或環境變數提供,命
HTTP 傳輸固定為無狀態:`/mcp` 只接受 POST,沒有 `Mcp-Session-Id`、獨立 SSE 與 `Last-Event-ID` 斷點續傳。伺服器會驗證來源,反向代理必須原樣轉發 `Mcp-Protocol-Version`、`Mcp-Method` 與 `Mcp-Name`。`Authorization: Bearer <令牌>` 與 `Authorization: token <令牌>` 會在每次請求中傳遞 Gitea 憑證,這是憑證透傳,而不是 MCP OAuth。 HTTP 傳輸固定為無狀態:`/mcp` 只接受 POST,沒有 `Mcp-Session-Id`、獨立 SSE 與 `Last-Event-ID` 斷點續傳。伺服器會驗證來源,反向代理必須原樣轉發 `Mcp-Protocol-Version`、`Mcp-Method` 與 `Mcp-Name`。`Authorization: Bearer <令牌>` 與 `Authorization: token <令牌>` 會在每次請求中傳遞 Gitea 憑證,這是憑證透傳,而不是 MCP OAuth。
HTTP 模式也會提供 `/healthz` 端點,伺服器正常運作時回傳 `200 OK`。Docker 映像內建的 `HEALTHCHECK` 會執行 `gitea-mcp -healthcheck`,它使用與 `-p`/`-port` 相同的連接埠(預設 `8080`)連線 `http://127.0.0.1:<連接埠>/healthz`,成功時結束碼為 `0`,失敗時為 `1`。stdio 部署不會提供 `/healthz`,因此在 stdio 模式下運作時應覆寫或停用映像內建的 `HEALTHCHECK`。
### Claude Code ### Claude Code
透過 `go run` 執行伺服器,需要安裝 [Go](https://go.dev): 透過 `go run` 執行伺服器,需要安裝 [Go](https://go.dev):
@@ -55,7 +57,7 @@ claude mcp add --transport stdio --scope user gitea \
"servers": { "servers": {
"gitea-mcp": { "gitea-mcp": {
"command": "docker", "command": "docker",
"args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "docker.gitea.com/gitea-mcp-server"], "args": ["run", "-i", "--rm", "-e", "GITEA_ACCESS_TOKEN", "git.i3omb.com/gronod/gitea-mcp-server"],
"env": { "env": {
"GITEA_ACCESS_TOKEN": "${input:gitea_token}" "GITEA_ACCESS_TOKEN": "${input:gitea_token}"
} }
@@ -91,7 +93,7 @@ claude mcp add --transport stdio --scope user gitea \
name = "gitea" name = "gitea"
transport = "stdio" transport = "stdio"
command = "docker" command = "docker"
args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "docker.gitea.com/gitea-mcp-server"] args = ["run", "--rm", "-i", "-e", "GITEA_ACCESS_TOKEN", "-e", "GITEA_HOST", "git.i3omb.com/gronod/gitea-mcp-server"]
[mcp_servers.env] [mcp_servers.env]
GITEA_ACCESS_TOKEN = "TOKEN" GITEA_ACCESS_TOKEN = "TOKEN"
@@ -156,12 +158,10 @@ Cursor 等客戶端可使用 stdio 命令:
| timetracking_write | timetracking | 寫入 | 寫入時間追蹤:計時器和記錄項目 | | timetracking_write | timetracking | 寫入 | 寫入時間追蹤:計時器和記錄項目 |
| package_read | packages | 讀取 | 讀取軟體套件註冊表:列出套件、列出版本或取得某個版本 | | package_read | packages | 讀取 | 讀取軟體套件註冊表:列出套件、列出版本或取得某個版本 |
| package_write | packages | 寫入 | 刪除軟體套件版本(不可復原) | | package_write | packages | 寫入 | 刪除軟體套件版本(不可復原) |
| project_read | project | 讀取 | 讀取專案:列出專案、取得專案、列出欄、取得欄或列出欄中的議題 |
| project_write | project | 寫入 | 寫入專案:建立、更新或刪除專案與欄;重新排序欄;新增、移除或移動議題 |
| list_issues | issue | 讀取 | 列出倉庫問題 | | list_issues | issue | 讀取 | 列出倉庫問題 |
| attachment_read | issue | 讀取 | 讀取問題/評論附件:列出中繼資料、取得中繼資料或下載內容 | | attachment_read | issue | 讀取 | 讀取問題/評論附件:列出中繼資料、取得中繼資料或下載內容 |
| issue_read | issue | 讀取 | 讀取問題:詳情、評論或標籤 | | issue_read | issue | 讀取 | 讀取問題:詳情、評論、標籤或阻塞關係 |
| issue_write | issue | 寫入 | 寫入問題:創建、更新、管理評論和標籤 | | issue_write | issue | 寫入 | 寫入問題:創建、更新、管理評論、標籤和阻塞關係 |
| list_pull_requests | pull_request | 讀取 | 列出倉庫拉取請求 | | list_pull_requests | pull_request | 讀取 | 列出倉庫拉取請求 |
| pull_request_read | pull_request | 讀取 | 讀取拉取請求:詳情、差異、變更檔案、頭部提交狀態、審查、審查評論 | | pull_request_read | pull_request | 讀取 | 讀取拉取請求:詳情、差異、變更檔案、頭部提交狀態、審查、審查評論 |
| pull_request_write | pull_request | 寫入 | 寫入拉取請求:創建、更新、關閉、重新開啟、合併、更新分支、管理審查者 | | pull_request_write | pull_request | 寫入 | 寫入拉取請求:創建、更新、關閉、重新開啟、合併、更新分支、管理審查者 |
@@ -182,6 +182,7 @@ Cursor 等客戶端可使用 stdio 命令:
| create_branch | branch | 寫入 | 創建新分支 | | create_branch | branch | 寫入 | 創建新分支 |
| delete_branch | branch | 寫入 | 刪除分支 | | delete_branch | branch | 寫入 | 刪除分支 |
| list_branches | branch | 讀取 | 列出倉庫分支 | | list_branches | branch | 讀取 | 列出倉庫分支 |
| rename_branch | branch | 寫入 | 重新命名分支 |
| create_tag | tag | 寫入 | 創建標籤 | | create_tag | tag | 寫入 | 創建標籤 |
| delete_tag | tag | 寫入 | 刪除標籤 | | delete_tag | tag | 寫入 | 刪除標籤 |
| get_tag | tag | 讀取 | 取得標籤詳情 | | get_tag | tag | 讀取 | 取得標籤詳情 |
+13
View File
@@ -5,6 +5,7 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"net/http"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@@ -23,9 +24,11 @@ var (
tools string tools string
scopes string scopes string
version bool version bool
healthcheck bool
maxInlineAttachmentBytes int maxInlineAttachmentBytes int
maxInlineAttachmentBytesFlagSet bool maxInlineAttachmentBytesFlagSet bool
osExit = os.Exit osExit = os.Exit
healthcheckClient = http.DefaultClient
) )
func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, readFile func(string) ([]byte, error), stderr io.Writer) { func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, readFile func(string) ([]byte, error), stderr io.Writer) {
@@ -53,6 +56,7 @@ func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, re
fs.BoolVar(&flagPkg.Insecure, "insecure", false, "") fs.BoolVar(&flagPkg.Insecure, "insecure", false, "")
fs.BoolVar(&version, "v", false, "") fs.BoolVar(&version, "v", false, "")
fs.BoolVar(&version, "version", false, "") fs.BoolVar(&version, "version", false, "")
fs.BoolVar(&healthcheck, "healthcheck", false, "")
maxInlineAttachmentBytes = 5 * 1024 * 1024 maxInlineAttachmentBytes = 5 * 1024 * 1024
fs.Func("max-inline-attachment-bytes", "", func(val string) error { fs.Func("max-inline-attachment-bytes", "", func(val string) error {
parsed, err := strconv.Atoi(val) parsed, err := strconv.Atoi(val)
@@ -81,6 +85,7 @@ func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, re
fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n") fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n")
fmt.Fprintf(w, " -max-inline-attachment-bytes <bytes>\tInline image attachments up to this size (default: 5242880)\n") fmt.Fprintf(w, " -max-inline-attachment-bytes <bytes>\tInline image attachments up to this size (default: 5242880)\n")
fmt.Fprintf(w, " -v, -version\tPrint version and exit\n") fmt.Fprintf(w, " -v, -version\tPrint version and exit\n")
fmt.Fprintf(w, " -healthcheck\tCheck a running HTTP server's /healthz endpoint and exit\n")
fmt.Fprintln(w) fmt.Fprintln(w)
fmt.Fprintln(w, "Environment variables:") fmt.Fprintln(w, "Environment variables:")
fmt.Fprintf(w, " GITEA_ACCESS_TOKEN\tProvide access token\n") fmt.Fprintf(w, " GITEA_ACCESS_TOKEN\tProvide access token\n")
@@ -183,6 +188,14 @@ func Execute() {
fmt.Fprintln(os.Stdout, flagPkg.Version) fmt.Fprintln(os.Stdout, flagPkg.Version)
return return
} }
if healthcheck {
if runHealthcheck(healthcheckClient, flagPkg.Port, os.Stdout, os.Stderr) {
osExit(0)
} else {
osExit(1)
}
return
}
if err := operation.Run(); err != nil { if err := operation.Run(); err != nil {
if err == context.Canceled { if err == context.Canceled {
log.Info("Server shutdown due to context cancellation") log.Info("Server shutdown due to context cancellation")
+9
View File
@@ -95,3 +95,12 @@ func TestInitFlagSetScopes(t *testing.T) {
}) })
} }
} }
func TestInitFlagSetHealthcheck(t *testing.T) {
t.Cleanup(func() { healthcheck = false })
fs := flag.NewFlagSet("test", flag.ContinueOnError)
initFlagSet(fs, []string{"-healthcheck"}, func(string) string { return "" }, func(string) ([]byte, error) { return nil, nil }, &bytes.Buffer{})
if !healthcheck {
t.Error("healthcheck = false, want true")
}
}
+29
View File
@@ -0,0 +1,29 @@
package cmd
import (
"fmt"
"io"
"net/http"
)
// runHealthcheck dials the /healthz endpoint on 127.0.0.1:port and reports
// success or failure. It returns true when the server responds with a 2xx
// status.
func runHealthcheck(client *http.Client, port int, stdout, stderr io.Writer) bool {
url := fmt.Sprintf("http://127.0.0.1:%d/healthz", port)
resp, err := client.Get(url)
if err != nil {
fmt.Fprintf(stderr, "healthcheck failed: %v\n", err)
return false
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
fmt.Fprintf(stderr, "healthcheck failed: unexpected status %s\n", resp.Status)
return false
}
fmt.Fprintln(stdout, "healthy")
return true
}
+81
View File
@@ -0,0 +1,81 @@
package cmd
import (
"bytes"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)
func TestRunHealthcheck(t *testing.T) {
tests := []struct {
name string
handler http.HandlerFunc
port func(server *httptest.Server) int
wantOK bool
wantStdout string
}{
{
name: "server responds 200 OK",
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
},
port: serverPort,
wantOK: true,
wantStdout: "healthy",
},
{
name: "server responds with an error status",
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
},
port: serverPort,
wantOK: false,
},
{
name: "nothing listening on the port",
port: func(*httptest.Server) int { return 1 },
wantOK: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var server *httptest.Server
if tt.handler != nil {
server = httptest.NewServer(tt.handler)
defer server.Close()
}
var stdout, stderr bytes.Buffer
ok := runHealthcheck(http.DefaultClient, tt.port(server), &stdout, &stderr)
if ok != tt.wantOK {
t.Errorf("runHealthcheck() = %v, want %v", ok, tt.wantOK)
}
if tt.wantStdout != "" && !strings.Contains(stdout.String(), tt.wantStdout) {
t.Errorf("stdout = %q, want it to contain %q", stdout.String(), tt.wantStdout)
}
if tt.wantOK && stderr.Len() != 0 {
t.Errorf("stderr = %q, want empty on success", stderr.String())
}
if !tt.wantOK && stderr.Len() == 0 {
t.Error("stderr is empty, want a failure message")
}
})
}
}
func serverPort(server *httptest.Server) int {
_, portStr, err := net.SplitHostPort(server.Listener.Addr().String())
if err != nil {
panic(err)
}
port, err := strconv.Atoi(portStr)
if err != nil {
panic(err)
}
return port
}
+7 -7
View File
@@ -1,11 +1,11 @@
module gitea.com/gitea/gitea-mcp module gitea.com/gitea/gitea-mcp
go 1.26.0 go 1.27
toolchain go1.26.6 toolchain go1.27.1
require ( require (
gitea.dev/sdk v1.2.1-0.20260822201514-76e7eafcee4b gitea.dev/sdk v1.2.0
github.com/modelcontextprotocol/go-sdk v1.7.0 github.com/modelcontextprotocol/go-sdk v1.7.0
go.uber.org/zap v1.28.0 go.uber.org/zap v1.28.0
go.uber.org/zap/exp v0.3.0 go.uber.org/zap/exp v0.3.0
@@ -17,14 +17,14 @@ require (
github.com/davidmz/go-pageant v1.0.2 // indirect github.com/davidmz/go-pageant v1.0.2 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect github.com/google/jsonschema-go v0.4.3 // indirect
github.com/hashicorp/go-version v1.9.0 // indirect github.com/hashicorp/go-version v1.9.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/asm v1.2.1 // indirect
github.com/segmentio/encoding v0.5.4 // indirect github.com/segmentio/encoding v0.5.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.uber.org/multierr v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.54.0 // indirect golang.org/x/crypto v0.56.0 // indirect
golang.org/x/oauth2 v0.35.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.22.0 // indirect golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect golang.org/x/sys v0.47.0 // indirect
golang.org/x/time v0.15.0 // indirect golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.47.0 // indirect golang.org/x/tools v0.49.0 // indirect
) )
+10 -10
View File
@@ -1,5 +1,5 @@
gitea.dev/sdk v1.2.1-0.20260822201514-76e7eafcee4b h1:Ub2tRd59s7zBxalMyaNyuwl2JA9/ZV4svGVbmV7itcU= gitea.dev/sdk v1.2.0 h1:avRtJl/nKCGispgSalo9czoZM9Rto1awnE0caNAoXGo=
gitea.dev/sdk v1.2.1-0.20260822201514-76e7eafcee4b/go.mod h1:McaA1Vd+POnguz48vHfgD9jWmeInt10eH/bKaCIVGDA= gitea.dev/sdk v1.2.0/go.mod h1:rfh5oNdIK24cbCREwIn1tqWKQW+IICXFGWJyebuOAOE=
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU= github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps= github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -18,8 +18,8 @@ github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6
github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
@@ -37,11 +37,11 @@ go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -54,8 +54,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+3 -3
View File
@@ -148,7 +148,7 @@ func listRepoActionSecretsFn(ctx context.Context, args map[string]any) (*mcp.Cal
} }
secrets, _, err := client.Actions.ListRepoSecrets(ctx, owner, repo, gitea_sdk.ListRepoActionsSecretOption{ secrets, _, err := client.Actions.ListRepoSecrets(ctx, owner, repo, gitea_sdk.ListRepoActionsSecretOption{
ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: pageSize}, Page: page, PageSize: pageSize,
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list repo action secrets err: %v", err)) return to.ErrorResult(fmt.Errorf("list repo action secrets err: %v", err))
@@ -228,7 +228,7 @@ func listOrgActionSecretsFn(ctx context.Context, args map[string]any) (*mcp.Call
} }
secrets, _, err := client.Actions.ListOrgSecrets(ctx, org, gitea_sdk.ListOrgActionsSecretOption{ secrets, _, err := client.Actions.ListOrgSecrets(ctx, org, gitea_sdk.ListOrgActionsSecretOption{
ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: pageSize}, Page: page, PageSize: pageSize,
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list org action secrets err: %v", err)) return to.ErrorResult(fmt.Errorf("list org action secrets err: %v", err))
@@ -428,7 +428,7 @@ func listOrgActionVariablesFn(ctx context.Context, args map[string]any) (*mcp.Ca
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err)) return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
} }
variables, _, err := client.Actions.ListOrgVariables(ctx, org, gitea_sdk.ListOrgActionsVariableOption{ variables, _, err := client.Actions.ListOrgVariables(ctx, org, gitea_sdk.ListOrgActionsVariableOption{
ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: pageSize}, Page: page, PageSize: pageSize,
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list org action variables err: %v", err)) return to.ErrorResult(fmt.Errorf("list org action variables err: %v", err))
+181
View File
@@ -0,0 +1,181 @@
package issue
import (
"context"
"fmt"
"net/http"
"net/url"
"gitea.com/gitea/gitea-mcp/pkg/gitea"
"gitea.com/gitea/gitea-mcp/pkg/params"
"gitea.com/gitea/gitea-mcp/pkg/to"
gitea_sdk "gitea.dev/sdk"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// issueMeta carries owner/repo in the body; the SDK's IssueMeta only has Index
// and Gitea resolves the body repo from those fields.
type issueMeta struct {
Index int64 `json:"index"`
Owner string `json:"owner"`
Repo string `json:"repo"`
}
func listIssueBlocksFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
owner, repo, index, err := issueRef(args)
if err != nil {
return to.ErrorResult(err)
}
page, pageSize := params.GetPagination(args, 30)
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
listOpt := gitea_sdk.ListOptions{Page: page, PageSize: pageSize}
issues, _, err := client.Issues.ListIssueBlocks(ctx, owner, repo, index, gitea_sdk.ListIssueBlocksOptions{
ListOptions: listOpt,
})
if err != nil {
return to.ErrorResult(fmt.Errorf("list %v/%v/issue/%v/blocks err: %v", owner, repo, index, err))
}
return to.TextResult(slimIssues(issues))
}
func blockIssueFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
return setIssueBlockingFn(ctx, args, true)
}
func unblockIssueFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
return setIssueBlockingFn(ctx, args, false)
}
func setIssueBlockingFn(ctx context.Context, args map[string]any, block bool) (*mcp.CallToolResult, error) {
owner, repo, index, err := issueRef(args)
if err != nil {
return to.ErrorResult(err)
}
blocked, err := params.GetIndex(args, "blocked_issue")
if err != nil {
return to.ErrorResult(err)
}
blockedOwner, blockedRepo := relatedIssueRepo(args, "blocked_owner", "blocked_repo", owner, repo)
method := http.MethodPost
if !block {
method = http.MethodDelete
}
var issue gitea_sdk.Issue
path := fmt.Sprintf("repos/%s/%s/issues/%d/blocks", url.PathEscape(owner), url.PathEscape(repo), index)
if _, err := gitea.DoJSON(ctx, method, path, nil, issueMeta{Index: blocked, Owner: blockedOwner, Repo: blockedRepo}, &issue); err != nil {
return to.ErrorResult(fmt.Errorf("update %v/%v/issue/%v/blocks err: %v", owner, repo, index, err))
}
return to.TextResult(slimIssue(&issue))
}
func listIssueDependenciesFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
owner, repo, index, err := issueRef(args)
if err != nil {
return to.ErrorResult(err)
}
page, pageSize := params.GetPagination(args, 30)
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
listOpt := gitea_sdk.ListOptions{Page: page, PageSize: pageSize}
issues, _, err := client.Issues.ListIssueDependencies(ctx, owner, repo, index, gitea_sdk.ListIssueDependenciesOptions{
ListOptions: listOpt,
})
if err != nil {
return to.ErrorResult(fmt.Errorf("list %v/%v/issue/%v/dependencies err: %v", owner, repo, index, err))
}
return to.TextResult(slimIssues(issues))
}
func addIssueDependencyFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
return setIssueDependencyFn(ctx, args, true)
}
func removeIssueDependencyFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
return setIssueDependencyFn(ctx, args, false)
}
func setIssueDependencyFn(ctx context.Context, args map[string]any, add bool) (*mcp.CallToolResult, error) {
owner, repo, index, err := issueRef(args)
if err != nil {
return to.ErrorResult(err)
}
blocking, err := params.GetIndex(args, "blocking_issue")
if err != nil {
return to.ErrorResult(err)
}
blockingOwner, blockingRepo := relatedIssueRepo(args, "blocking_owner", "blocking_repo", owner, repo)
method := http.MethodPost
if !add {
method = http.MethodDelete
}
var issue gitea_sdk.Issue
path := fmt.Sprintf("repos/%s/%s/issues/%d/dependencies", url.PathEscape(owner), url.PathEscape(repo), index)
if _, err := gitea.DoJSON(ctx, method, path, nil, issueMeta{Index: blocking, Owner: blockingOwner, Repo: blockingRepo}, &issue); err != nil {
return to.ErrorResult(fmt.Errorf("update %v/%v/issue/%v/dependencies err: %v", owner, repo, index, err))
}
return to.TextResult(slimIssue(&issue))
}
func checkIssueBlockedFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
owner, repo, index, err := issueRef(args)
if err != nil {
return to.ErrorResult(err)
}
page, pageSize := params.GetPagination(args, 30)
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
listOpt := gitea_sdk.ListOptions{Page: page, PageSize: pageSize}
issues, _, err := client.Issues.ListIssueDependencies(ctx, owner, repo, index, gitea_sdk.ListIssueDependenciesOptions{
ListOptions: listOpt,
})
if err != nil {
return to.ErrorResult(fmt.Errorf("list %v/%v/issue/%v/dependencies err: %v", owner, repo, index, err))
}
openBlockers := make([]map[string]any, 0)
for _, issue := range issues {
if issue == nil {
continue
}
if issue.State == gitea_sdk.StateOpen || issue.State == "" {
openBlockers = append(openBlockers, slimIssue(issue))
}
}
return to.TextResult(map[string]any{
"blocked": len(openBlockers) > 0,
"total_dependencies": len(issues),
"open_blockers": len(openBlockers),
"blockers": slimIssues(issues),
"open": openBlockers,
})
}
func relatedIssueRepo(args map[string]any, ownerKey, repoKey, owner, repo string) (string, string) {
if o := params.GetOptionalString(args, ownerKey, ""); o != "" {
owner = o
}
if r := params.GetOptionalString(args, repoKey, ""); r != "" {
repo = r
}
return owner, repo
}
func issueRef(args map[string]any) (owner, repo string, index int64, err error) {
if owner, err = params.GetString(args, "owner"); err != nil {
return "", "", 0, err
}
if repo, err = params.GetString(args, "repo"); err != nil {
return "", "", 0, err
}
if index, err = params.GetIndex(args, "issue_number"); err != nil {
return "", "", 0, err
}
return owner, repo, index, nil
}
+207
View File
@@ -0,0 +1,207 @@
package issue
import (
"context"
"encoding/json"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"strings"
"testing"
"gitea.com/gitea/gitea-mcp/pkg/flag"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func Test_issueBlocking(t *testing.T) {
const (
owner = "octo"
repo = "demo"
)
blocksPath := fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/blocks", owner, repo)
depsPath := fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/dependencies", owner, repo)
tests := []struct {
name string
fn func(context.Context, map[string]any) (*mcp.CallToolResult, error)
args map[string]any
wantPath string
wantMethod string
wantQuery string
wantIndex float64
wantOwner string
wantRepo string
wantBody string
}{
{
name: "list blocks paginates",
fn: listIssueBlocksFn,
args: map[string]any{"page": float64(2), "per_page": float64(10)},
wantPath: blocksPath,
wantMethod: http.MethodGet,
wantQuery: "limit=10&page=2",
},
{
name: "block issue posts index",
fn: blockIssueFn,
args: map[string]any{"blocked_issue": float64(7)},
wantPath: blocksPath,
wantMethod: http.MethodPost,
wantIndex: 7,
wantOwner: owner,
wantRepo: repo,
},
{
name: "block issue posts cross-repo target",
fn: blockIssueFn,
args: map[string]any{
"blocked_issue": float64(7),
"blocked_owner": "other",
"blocked_repo": "elsewhere",
},
wantPath: blocksPath,
wantMethod: http.MethodPost,
wantIndex: 7,
wantOwner: "other",
wantRepo: "elsewhere",
},
{
name: "unblock issue deletes with index",
fn: unblockIssueFn,
args: map[string]any{"blocked_issue": float64(7)},
wantPath: blocksPath,
wantMethod: http.MethodDelete,
wantIndex: 7,
wantOwner: owner,
wantRepo: repo,
},
{
name: "list dependencies paginates",
fn: listIssueDependenciesFn,
args: map[string]any{"page": float64(3), "per_page": float64(5)},
wantPath: depsPath,
wantMethod: http.MethodGet,
wantQuery: "limit=5&page=3",
},
{
name: "add dependency posts index",
fn: addIssueDependencyFn,
args: map[string]any{"blocking_issue": float64(9)},
wantPath: depsPath,
wantMethod: http.MethodPost,
wantIndex: 9,
wantOwner: owner,
wantRepo: repo,
},
{
name: "add dependency posts cross-repo target",
fn: addIssueDependencyFn,
args: map[string]any{
"blocking_issue": float64(9),
"blocking_owner": "other",
"blocking_repo": "elsewhere",
},
wantPath: depsPath,
wantMethod: http.MethodPost,
wantIndex: 9,
wantOwner: "other",
wantRepo: "elsewhere",
},
{
name: "remove dependency deletes with index",
fn: removeIssueDependencyFn,
args: map[string]any{"blocking_issue": float64(9)},
wantPath: depsPath,
wantMethod: http.MethodDelete,
wantIndex: 9,
wantOwner: owner,
wantRepo: repo,
},
{
name: "check blocked summarizes open dependencies",
fn: checkIssueBlockedFn,
args: map[string]any{"page": float64(1), "per_page": float64(30)},
wantPath: depsPath,
wantMethod: http.MethodGet,
wantQuery: "limit=30&page=1",
wantBody: `"blocked":true`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var (
gotMethod string
gotPath string
gotQuery string
gotBody map[string]any
)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/version":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"version":"1.27.2"}`))
case blocksPath, depsPath:
gotMethod = r.Method
gotPath = r.URL.Path
gotQuery = r.URL.RawQuery
_ = json.NewDecoder(r.Body).Decode(&gotBody)
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodGet {
_, _ = w.Write([]byte(`[{"number":7,"title":"blocked","state":"open"}]`))
} else {
_, _ = w.Write([]byte(`{"number":7,"title":"blocked","state":"open"}`))
}
default:
http.NotFound(w, r)
}
})
server := httptest.NewServer(handler)
defer server.Close()
origHost, origToken, origVersion := flag.Host, flag.Token, flag.Version
flag.Host, flag.Token, flag.Version = server.URL, "", "test"
defer func() { flag.Host, flag.Token, flag.Version = origHost, origToken, origVersion }()
args := map[string]any{"owner": owner, "repo": repo, "issue_number": float64(42)}
maps.Copy(args, tt.args)
res, err := tt.fn(context.Background(), args)
if err != nil {
t.Fatalf("handler error = %v", err)
}
if res.IsError {
t.Fatalf("unexpected error result: %v", res.Content)
}
if gotMethod != tt.wantMethod {
t.Fatalf("method = %s, want %s", gotMethod, tt.wantMethod)
}
if gotPath != tt.wantPath {
t.Fatalf("path = %s, want %s", gotPath, tt.wantPath)
}
if tt.wantQuery != "" && gotQuery != tt.wantQuery {
t.Fatalf("query = %s, want %s", gotQuery, tt.wantQuery)
}
if tt.wantIndex != 0 {
if gotBody["index"] != tt.wantIndex {
t.Fatalf("body index = %v, want %v", gotBody["index"], tt.wantIndex)
}
if gotBody["owner"] != tt.wantOwner {
t.Fatalf("body owner = %v, want %s", gotBody["owner"], tt.wantOwner)
}
if gotBody["repo"] != tt.wantRepo {
t.Fatalf("body repo = %v, want %s", gotBody["repo"], tt.wantRepo)
}
}
body := res.Content[0].(*mcp.TextContent).Text
if tt.wantBody != "" {
if !strings.Contains(body, tt.wantBody) {
t.Fatalf("expected %s in output, got: %s", tt.wantBody, body)
}
} else if !strings.Contains(body, `"number":7`) && !strings.Contains(body, `"number": 7`) {
t.Fatalf("expected slim issue in output, got: %s", body)
}
})
}
}
+26 -6
View File
@@ -55,19 +55,21 @@ var (
IssueReadTool = tool.NewDefinition( IssueReadTool = tool.NewDefinition(
IssueReadToolName, IssueReadToolName,
"Read issue: details, comments, or labels.", "Read issue: details, comments, labels, or dependency/blocking links. list_dependencies is issues that block this one (blocked-by); list_blocks is issues this one blocks. check_blocked summarizes whether any of those dependencies are still open. These methods 404 if the repo has issue dependencies disabled.",
annotation.ReadOnly("Read issue details"), annotation.ReadOnly("Read issue details"),
tool.String("method", tool.Required(), tool.Enum("get", "get_comments", "get_labels")), tool.String("method", tool.Required(), tool.Enum("get", "get_comments", "get_labels", "list_blocks", "list_dependencies", "check_blocked")),
tool.String("owner", tool.Required(), tool.Description(params.OwnerDesc)), tool.String("owner", tool.Required(), tool.Description(params.OwnerDesc)),
tool.String("repo", tool.Required(), tool.Description(params.RepoDesc)), tool.String("repo", tool.Required(), tool.Description(params.RepoDesc)),
tool.Number("issue_number", tool.Required()), tool.Number("issue_number", tool.Required()),
tool.Number("page", tool.Description(params.PageDesc), tool.Default(1)),
tool.Number("per_page", tool.Description(params.PaginationDesc), tool.Default(30)),
) )
IssueWriteTool = tool.NewDefinition( IssueWriteTool = tool.NewDefinition(
IssueWriteToolName, IssueWriteToolName,
"Write issues: create, update, manage comments and labels.", "Write issues: create, update, manage comments, labels, and dependency/blocking links. block_issue makes issue_number block blocked_issue; add_dependency makes issue_number depend on blocking_issue. Cross-repo links use blocked_owner/blocked_repo or blocking_owner/blocking_repo (instance must allow cross-repository dependencies). Repo must have issue dependencies enabled or Gitea returns 404.",
annotation.Write("Create or update issues, comments, and labels"), annotation.Write("Create or update issues, comments, and labels"),
tool.String("method", tool.Required(), tool.Enum("create", "update", "add_comment", "edit_comment", "add_labels", "remove_label", "replace_labels", "clear_labels")), tool.String("method", tool.Required(), tool.Enum("create", "update", "add_comment", "edit_comment", "add_labels", "remove_label", "replace_labels", "clear_labels", "block_issue", "unblock_issue", "add_dependency", "remove_dependency")),
tool.String("owner", tool.Required(), tool.Description(params.OwnerDesc)), tool.String("owner", tool.Required(), tool.Description(params.OwnerDesc)),
tool.String("repo", tool.Required(), tool.Description(params.RepoDesc)), tool.String("repo", tool.Required(), tool.Description(params.RepoDesc)),
tool.Number("issue_number", tool.Description("required except for 'create'")), tool.Number("issue_number", tool.Description("required except for 'create'")),
@@ -82,6 +84,12 @@ var (
tool.String("ref", tool.Description("branch to associate")), tool.String("ref", tool.Description("branch to associate")),
tool.String("deadline", tool.Description("ISO 8601")), tool.String("deadline", tool.Description("ISO 8601")),
tool.Boolean("remove_deadline"), tool.Boolean("remove_deadline"),
tool.Number("blocked_issue", tool.Description("issue number that issue_number blocks (required for 'block_issue'/'unblock_issue')")),
tool.String("blocked_owner", tool.Description("owner of blocked_issue; defaults to owner")),
tool.String("blocked_repo", tool.Description("repo of blocked_issue; defaults to repo")),
tool.Number("blocking_issue", tool.Description("issue number that blocks issue_number (required for 'add_dependency'/'remove_dependency')")),
tool.String("blocking_owner", tool.Description("owner of blocking_issue; defaults to owner")),
tool.String("blocking_repo", tool.Description("repo of blocking_issue; defaults to repo")),
) )
) )
@@ -112,6 +120,12 @@ func issueReadFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult,
return getIssueCommentsByIndexFn(ctx, args) return getIssueCommentsByIndexFn(ctx, args)
case "get_labels": case "get_labels":
return getIssueLabelsFn(ctx, args) return getIssueLabelsFn(ctx, args)
case "list_blocks":
return listIssueBlocksFn(ctx, args)
case "list_dependencies":
return listIssueDependenciesFn(ctx, args)
case "check_blocked":
return checkIssueBlockedFn(ctx, args)
default: default:
return to.ErrorResult(fmt.Errorf("unknown method: %s", method)) return to.ErrorResult(fmt.Errorf("unknown method: %s", method))
} }
@@ -139,6 +153,14 @@ func issueWriteFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult
return replaceIssueLabelsFn(ctx, args) return replaceIssueLabelsFn(ctx, args)
case "clear_labels": case "clear_labels":
return clearIssueLabelsFn(ctx, args) return clearIssueLabelsFn(ctx, args)
case "block_issue":
return blockIssueFn(ctx, args)
case "unblock_issue":
return unblockIssueFn(ctx, args)
case "add_dependency":
return addIssueDependencyFn(ctx, args)
case "remove_dependency":
return removeIssueDependencyFn(ctx, args)
default: default:
return to.ErrorResult(fmt.Errorf("unknown method: %s", method)) return to.ErrorResult(fmt.Errorf("unknown method: %s", method))
} }
@@ -187,10 +209,8 @@ func listRepoIssuesFn(ctx context.Context, args map[string]any) (*mcp.CallToolRe
State: gitea_sdk.StateType(state), State: gitea_sdk.StateType(state),
Labels: labels, Labels: labels,
Milestones: milestones, Milestones: milestones,
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
switch args["type"] { switch args["type"] {
case "issues": case "issues":
-2
View File
@@ -11,7 +11,6 @@ func slimIssue(i *gitea_sdk.Issue) map[string]any {
return nil return nil
} }
m := map[string]any{ m := map[string]any{
"id": i.ID,
"number": i.Index, "number": i.Index,
"title": i.Title, "title": i.Title,
"body": i.Body, "body": i.Body,
@@ -52,7 +51,6 @@ func slimIssues(issues []*gitea_sdk.Issue) []map[string]any {
continue continue
} }
m := map[string]any{ m := map[string]any{
"id": i.ID,
"number": i.Index, "number": i.Index,
"title": i.Title, "title": i.Title,
"state": i.State, "state": i.State,
-4
View File
@@ -8,7 +8,6 @@ import (
func TestSlimIssue(t *testing.T) { func TestSlimIssue(t *testing.T) {
i := &gitea_sdk.Issue{ i := &gitea_sdk.Issue{
ID: 99,
Index: 42, Index: 42,
Title: "Bug report", Title: "Bug report",
Body: "Something is broken", Body: "Something is broken",
@@ -25,9 +24,6 @@ func TestSlimIssue(t *testing.T) {
m := slimIssue(i) m := slimIssue(i)
if m["id"] != int64(99) {
t.Errorf("expected id 99, got %v", m["id"])
}
if m["number"] != int64(42) { if m["number"] != int64(42) {
t.Errorf("expected number 42, got %v", m["number"]) t.Errorf("expected number 42, got %v", m["number"])
} }
-4
View File
@@ -116,10 +116,8 @@ func listRepoLabelsFn(ctx context.Context, args map[string]any) (*mcp.CallToolRe
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListLabelsOptions{ opt := gitea_sdk.ListLabelsOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
@@ -261,10 +259,8 @@ func listOrgLabelsFn(ctx context.Context, args map[string]any) (*mcp.CallToolRes
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListOrgLabelsOptions{ opt := gitea_sdk.ListOrgLabelsOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
-2
View File
@@ -136,10 +136,8 @@ func listMilestonesFn(ctx context.Context, args map[string]any) (*mcp.CallToolRe
opt := gitea_sdk.ListMilestoneOption{ opt := gitea_sdk.ListMilestoneOption{
State: gitea_sdk.StateType(state), State: gitea_sdk.StateType(state),
Name: name, Name: name,
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
-2
View File
@@ -95,10 +95,8 @@ func notificationWriteFn(ctx context.Context, args map[string]any) (*mcp.CallToo
func listNotificationsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) { func listNotificationsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListNotificationOptions{ opt := gitea_sdk.ListNotificationOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
if status, ok := args["status"].(string); ok { if status, ok := args["status"].(string); ok {
opt.Status = []gitea_sdk.NotificationStatus{gitea_sdk.NotificationStatus(status)} opt.Status = []gitea_sdk.NotificationStatus{gitea_sdk.NotificationStatus(status)}
+8 -2
View File
@@ -19,7 +19,6 @@ import (
"gitea.com/gitea/gitea-mcp/operation/milestone" "gitea.com/gitea/gitea-mcp/operation/milestone"
"gitea.com/gitea/gitea-mcp/operation/notification" "gitea.com/gitea/gitea-mcp/operation/notification"
"gitea.com/gitea/gitea-mcp/operation/packages" "gitea.com/gitea/gitea-mcp/operation/packages"
"gitea.com/gitea/gitea-mcp/operation/project"
"gitea.com/gitea/gitea-mcp/operation/pull" "gitea.com/gitea/gitea-mcp/operation/pull"
"gitea.com/gitea/gitea-mcp/operation/repo" "gitea.com/gitea/gitea-mcp/operation/repo"
"gitea.com/gitea/gitea-mcp/operation/search" "gitea.com/gitea/gitea-mcp/operation/search"
@@ -48,7 +47,7 @@ var (
domainTools = []*tool.Tool{ domainTools = []*tool.Tool{
user.Tool, actions.Tool, repo.Tool, notification.Tool, issue.Tool, user.Tool, actions.Tool, repo.Tool, notification.Tool, issue.Tool,
label.Tool, milestone.Tool, packages.Tool, pull.Tool, search.Tool, label.Tool, milestone.Tool, packages.Tool, pull.Tool, search.Tool,
project.Tool, version.Tool, wiki.Tool, timetracking.Tool, version.Tool, wiki.Tool, timetracking.Tool,
repo.FileTool, repo.BranchTool, repo.TagTool, repo.CommitTool, repo.ReleaseTool, repo.FileTool, repo.BranchTool, repo.TagTool, repo.CommitTool, repo.ReleaseTool,
} }
) )
@@ -134,6 +133,7 @@ func newHTTPServer(addr string, s *mcp.Server) *http.Server {
PropagateRequestCancellation: true, PropagateRequestCancellation: true,
}, },
))) )))
mux.HandleFunc("/healthz", handleHealthz)
return &http.Server{ return &http.Server{
Addr: addr, Addr: addr,
Handler: mux, Handler: mux,
@@ -141,6 +141,12 @@ func newHTTPServer(addr string, s *mcp.Server) *http.Server {
} }
} }
func handleHealthz(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
}
func Run() error { func Run() error {
mcpServer = newMCPServer(flag.Version) mcpServer = newMCPServer(flag.Version)
RegisterTool(mcpServer) RegisterTool(mcpServer)
+20 -1
View File
@@ -1,6 +1,10 @@
package operation package operation
import "testing" import (
"net/http"
"net/http/httptest"
"testing"
)
func TestNewHTTPServerConfig(t *testing.T) { func TestNewHTTPServerConfig(t *testing.T) {
server := newHTTPServer(":12345", newMCPServer("test")) server := newHTTPServer(":12345", newMCPServer("test"))
@@ -18,6 +22,21 @@ func TestNewHTTPServerConfig(t *testing.T) {
} }
} }
func TestHealthzEndpoint(t *testing.T) {
server := newHTTPServer(":0", newMCPServer("test"))
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
rec := httptest.NewRecorder()
server.Handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
}
if body := rec.Body.String(); body == "" {
t.Error("body is empty, want a non-empty health message")
}
}
func TestParseAuthToken(t *testing.T) { func TestParseAuthToken(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
-608
View File
@@ -1,608 +0,0 @@
package project
import (
"context"
"errors"
"fmt"
"gitea.com/gitea/gitea-mcp/pkg/annotation"
"gitea.com/gitea/gitea-mcp/pkg/gitea"
"gitea.com/gitea/gitea-mcp/pkg/params"
"gitea.com/gitea/gitea-mcp/pkg/to"
"gitea.com/gitea/gitea-mcp/pkg/tool"
gitea_sdk "gitea.dev/sdk"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
var Tool = tool.New("project")
const (
ProjectReadToolName = "project_read"
ProjectWriteToolName = "project_write"
)
var (
ProjectReadTool = tool.NewDefinition(
ProjectReadToolName,
"Read projects: list projects, get a project, list columns, get a column, or list issues in a column.",
annotation.ReadOnly("Read projects"),
tool.String("method", tool.Required(), tool.Enum("list", "get", "list_columns", "get_column", "list_column_issues")),
tool.String("scope", tool.Required(), tool.Enum("repo", "org", "user", "current_user")),
tool.String("owner", tool.Description("repo owner for 'repo' scope, org name for 'org' scope, username for 'user' scope")),
tool.String("repo", tool.Description("repo name for 'repo' scope")),
tool.String("state", tool.Default("all"), tool.Enum("open", "closed", "all")),
tool.Number("project_id", tool.Description("project ID for 'get' and column methods")),
tool.Number("column_id", tool.Description("column ID for 'get_column' and 'list_column_issues'")),
tool.Number("page", tool.Description(params.PageDesc), tool.Default(1), tool.Minimum(1)),
tool.Number("per_page", tool.Description(params.PaginationDesc), tool.Default(30), tool.Minimum(1)),
)
ProjectWriteTool = tool.NewDefinition(
ProjectWriteToolName,
"Write projects: create, update, or delete projects and columns; reorder columns; add, remove, or move issues.",
annotation.Destructive("Create, update, or delete projects and project columns"),
tool.String("method", tool.Required(), tool.Enum("create", "update", "delete", "create_column", "update_column", "delete_column", "set_default_column", "move_columns", "add_issue", "remove_issue", "move_issue")),
tool.String("scope", tool.Required(), tool.Enum("repo", "org", "current_user")),
tool.String("owner", tool.Description("repo owner for 'repo' scope, org name for 'org' scope")),
tool.String("repo", tool.Description("repo name for 'repo' scope")),
tool.Number("project_id", tool.Description("project ID (required except for 'create')")),
tool.Number("column_id", tool.Description("column ID (required for column and issue methods)")),
tool.Number("issue_id", tool.Description("global issue ID (required for 'add_issue', 'remove_issue', and 'move_issue')")),
tool.String("title", tool.Description("for 'create', 'update', 'create_column', and 'update_column'")),
tool.String("description", tool.Description("for 'create' and 'update'")),
tool.String("template_type", tool.Enum("none", "basic_kanban", "bug_triage")),
tool.String("card_type", tool.Enum("text_only", "images_and_text")),
tool.String("state", tool.Enum("open", "closed")),
tool.String("color", tool.Description("6-digit hex column color, e.g. #FF0000")),
tool.Number("sorting", tool.Description("position for 'update_column' and 'move_issue'")),
tool.Array("column_ids", tool.Description("ordered column IDs for 'move_columns'"), tool.Items(map[string]any{"type": "number"})),
)
)
func init() {
Tool.RegisterRead(tool.ServerTool{
Tool: ProjectReadTool,
Handler: projectReadFn,
})
Tool.RegisterWrite(tool.ServerTool{
Tool: ProjectWriteTool,
Handler: projectWriteFn,
})
}
type projectScopeInfo struct {
scope gitea_sdk.ProjectScope
kind string
}
func getProjectScope(args map[string]any, writable bool) (projectScopeInfo, error) {
scopeName := params.GetOptionalString(args, "scope", "")
switch scopeName {
case "repo":
owner, err := params.GetString(args, "owner")
if err != nil {
return projectScopeInfo{}, err
}
repo, err := params.GetString(args, "repo")
if err != nil {
return projectScopeInfo{}, err
}
return projectScopeInfo{scope: gitea_sdk.RepoProjectScope(owner, repo), kind: "repo"}, nil
case "org":
owner, err := params.GetString(args, "owner")
if err != nil {
return projectScopeInfo{}, err
}
return projectScopeInfo{scope: gitea_sdk.OrgProjectScope(owner), kind: "org"}, nil
case "user":
owner, err := params.GetString(args, "owner")
if err != nil {
return projectScopeInfo{}, err
}
if writable {
return projectScopeInfo{}, errors.New("scope 'user' only supports listing projects")
}
return projectScopeInfo{scope: gitea_sdk.UserProjectScope(owner), kind: "user"}, nil
case "current_user":
return projectScopeInfo{scope: gitea_sdk.CurrentUserProjectScope(), kind: "current_user"}, nil
default:
if scopeName == "" {
return projectScopeInfo{}, errors.New("scope is required")
}
return projectScopeInfo{}, fmt.Errorf("unknown scope: %s", scopeName)
}
}
func projectReadFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
method, err := params.GetString(args, "method")
if err != nil {
return to.ErrorResult(err)
}
switch method {
case "list":
return listProjectsFn(ctx, args)
case "get":
return getProjectFn(ctx, args)
case "list_columns":
return listProjectColumnsFn(ctx, args)
case "get_column":
return getProjectColumnFn(ctx, args)
case "list_column_issues":
return listProjectColumnIssuesFn(ctx, args)
default:
return to.ErrorResult(fmt.Errorf("unknown method: %s", method))
}
}
func projectWriteFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
method, err := params.GetString(args, "method")
if err != nil {
return to.ErrorResult(err)
}
switch method {
case "create":
return createProjectFn(ctx, args)
case "update":
return updateProjectFn(ctx, args)
case "delete":
return deleteProjectFn(ctx, args)
case "create_column":
return createProjectColumnFn(ctx, args)
case "update_column":
return updateProjectColumnFn(ctx, args)
case "delete_column":
return deleteProjectColumnFn(ctx, args)
case "set_default_column":
return setDefaultProjectColumnFn(ctx, args)
case "move_columns":
return moveProjectColumnsFn(ctx, args)
case "add_issue":
return addIssueToProjectColumnFn(ctx, args)
case "remove_issue":
return removeIssueFromProjectColumnFn(ctx, args)
case "move_issue":
return moveProjectIssueFn(ctx, args)
default:
return to.ErrorResult(fmt.Errorf("unknown method: %s", method))
}
}
func listProjectsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, false)
if err != nil {
return to.ErrorResult(err)
}
state := params.GetOptionalString(args, "state", "all")
page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListProjectsOptions{
State: gitea_sdk.StateType(state),
ListOptions: gitea_sdk.ListOptions{
Page: page,
PageSize: pageSize,
},
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
projects, _, err := client.Projects.ListProjects(ctx, info.scope, opt)
if err != nil {
return to.ErrorResult(fmt.Errorf("list projects err: %v", err))
}
return to.TextResult(slimProjects(projects))
}
func getProjectFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, false)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
project, _, err := client.Projects.GetProject(ctx, info.scope, projectID)
if err != nil {
return to.ErrorResult(fmt.Errorf("get project/%d err: %v", projectID, err))
}
return to.TextResult(slimProject(project))
}
func listProjectColumnsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, false)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
page, pageSize := params.GetPagination(args, 30)
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
columns, _, err := client.Projects.ListProjectColumns(ctx, info.scope, projectID, gitea_sdk.ListOptions{
Page: page,
PageSize: pageSize,
})
if err != nil {
return to.ErrorResult(fmt.Errorf("list project/%d/columns err: %v", projectID, err))
}
return to.TextResult(slimProjectColumns(columns))
}
func getProjectColumnFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, false)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
column, _, err := client.Projects.GetProjectColumn(ctx, info.scope, projectID, columnID)
if err != nil {
return to.ErrorResult(fmt.Errorf("get project/%d/columns/%d err: %v", projectID, columnID, err))
}
return to.TextResult(slimProjectColumn(column))
}
func listProjectColumnIssuesFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, false)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
page, pageSize := params.GetPagination(args, 30)
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
issues, _, err := client.Projects.ListProjectColumnIssues(ctx, info.scope, projectID, columnID, gitea_sdk.ListOptions{
Page: page,
PageSize: pageSize,
})
if err != nil {
return to.ErrorResult(fmt.Errorf("list project/%d/columns/%d/issues err: %v", projectID, columnID, err))
}
return to.TextResult(slimProjectIssues(issues))
}
func createProjectFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
title, err := params.GetString(args, "title")
if err != nil {
return to.ErrorResult(err)
}
opt := gitea_sdk.CreateProjectOption{Title: title}
if description, ok := args["description"].(string); ok {
opt.Description = description
}
if templateType, ok := args["template_type"].(string); ok {
opt.TemplateType = gitea_sdk.ProjectTemplateType(templateType)
}
if cardType, ok := args["card_type"].(string); ok {
opt.CardType = gitea_sdk.ProjectCardType(cardType)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
project, _, err := client.Projects.CreateProject(ctx, info.scope, opt)
if err != nil {
return to.ErrorResult(fmt.Errorf("create project err: %v", err))
}
return to.TextResult(slimProject(project))
}
func updateProjectFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
opt := gitea_sdk.EditProjectOption{
Title: params.GetPresentStringPtr(args, "title"),
Description: params.GetPresentStringPtr(args, "description"),
}
if cardType, ok := args["card_type"].(string); ok {
value := gitea_sdk.ProjectCardType(cardType)
opt.CardType = &value
}
if state, ok := args["state"].(string); ok {
value := gitea_sdk.StateType(state)
opt.State = &value
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
project, _, err := client.Projects.EditProject(ctx, info.scope, projectID, opt)
if err != nil {
return to.ErrorResult(fmt.Errorf("update project/%d err: %v", projectID, err))
}
return to.TextResult(slimProject(project))
}
func deleteProjectFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
_, err = client.Projects.DeleteProject(ctx, info.scope, projectID)
if err != nil {
return to.ErrorResult(fmt.Errorf("delete project/%d err: %v", projectID, err))
}
return to.TextResult("Project deleted successfully")
}
func createProjectColumnFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
title, err := params.GetString(args, "title")
if err != nil {
return to.ErrorResult(err)
}
opt := gitea_sdk.CreateProjectColumnOption{Title: title}
if color, ok := args["color"].(string); ok {
opt.Color = color
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
column, _, err := client.Projects.CreateProjectColumn(ctx, info.scope, projectID, opt)
if err != nil {
return to.ErrorResult(fmt.Errorf("create project/%d/column err: %v", projectID, err))
}
return to.TextResult(slimProjectColumn(column))
}
func updateProjectColumnFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
opt := gitea_sdk.EditProjectColumnOption{
Title: params.GetPresentStringPtr(args, "title"),
Color: params.GetPresentStringPtr(args, "color"),
}
if sorting, ok := optionalIntPtr(args, "sorting"); ok {
opt.Sorting = sorting
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
column, _, err := client.Projects.EditProjectColumn(ctx, info.scope, projectID, columnID, opt)
if err != nil {
return to.ErrorResult(fmt.Errorf("update project/%d/columns/%d err: %v", projectID, columnID, err))
}
return to.TextResult(slimProjectColumn(column))
}
func deleteProjectColumnFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
_, err = client.Projects.DeleteProjectColumn(ctx, info.scope, projectID, columnID)
if err != nil {
return to.ErrorResult(fmt.Errorf("delete project/%d/columns/%d err: %v", projectID, columnID, err))
}
return to.TextResult("Project column deleted successfully")
}
func setDefaultProjectColumnFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
_, err = client.Projects.SetDefaultProjectColumn(ctx, info.scope, projectID, columnID)
if err != nil {
return to.ErrorResult(fmt.Errorf("set project/%d default column/%d err: %v", projectID, columnID, err))
}
return to.TextResult("Project default column set successfully")
}
func moveProjectColumnsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnIDs, err := params.GetInt64Slice(args, "column_ids")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
_, err = client.Projects.MoveProjectColumns(ctx, info.scope, projectID, gitea_sdk.MoveProjectColumnsOption{ColumnIDs: columnIDs})
if err != nil {
return to.ErrorResult(fmt.Errorf("move project/%d columns err: %v", projectID, err))
}
return to.TextResult("Project columns moved successfully")
}
func addIssueToProjectColumnFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
issueID, err := params.GetIndex(args, "issue_id")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
_, err = client.Projects.AddIssueToProjectColumn(ctx, info.scope, projectID, columnID, issueID)
if err != nil {
return to.ErrorResult(fmt.Errorf("add issue/%d to project/%d/columns/%d err: %v", issueID, projectID, columnID, err))
}
return to.TextResult("Issue added to project column successfully")
}
func removeIssueFromProjectColumnFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
issueID, err := params.GetIndex(args, "issue_id")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
_, err = client.Projects.RemoveIssueFromProjectColumn(ctx, info.scope, projectID, columnID, issueID)
if err != nil {
return to.ErrorResult(fmt.Errorf("remove issue/%d from project/%d/columns/%d err: %v", issueID, projectID, columnID, err))
}
return to.TextResult("Issue removed from project column successfully")
}
func moveProjectIssueFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
info, err := getProjectScope(args, true)
if err != nil {
return to.ErrorResult(err)
}
projectID, err := params.GetIndex(args, "project_id")
if err != nil {
return to.ErrorResult(err)
}
issueID, err := params.GetIndex(args, "issue_id")
if err != nil {
return to.ErrorResult(err)
}
columnID, err := params.GetIndex(args, "column_id")
if err != nil {
return to.ErrorResult(err)
}
opt := gitea_sdk.MoveProjectIssueOption{ColumnID: columnID}
if sorting, ok := optionalInt64Ptr(args, "sorting"); ok {
opt.Sorting = sorting
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
_, err = client.Projects.MoveProjectIssue(ctx, info.scope, projectID, issueID, opt)
if err != nil {
return to.ErrorResult(fmt.Errorf("move issue/%d in project/%d err: %v", issueID, projectID, err))
}
return to.TextResult("Project issue moved successfully")
}
func optionalIntPtr(args map[string]any, key string) (*int, bool) {
value, ok := params.ToInt64(args[key])
if !ok {
return nil, false
}
converted := int(value)
return &converted, true
}
func optionalInt64Ptr(args map[string]any, key string) (*int64, bool) {
value, ok := params.ToInt64(args[key])
if !ok {
return nil, false
}
return &value, true
}
-517
View File
@@ -1,517 +0,0 @@
package project
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
mcpContext "gitea.com/gitea/gitea-mcp/pkg/context"
"gitea.com/gitea/gitea-mcp/pkg/flag"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestGetProjectScope(t *testing.T) {
tests := []struct {
name string
args map[string]any
writable bool
wantKind string
wantErr bool
}{
{
name: "repo",
args: map[string]any{"scope": "repo", "owner": "octo", "repo": "demo"},
wantKind: "repo",
},
{
name: "org",
args: map[string]any{"scope": "org", "owner": "acme"},
wantKind: "org",
},
{
name: "user read",
args: map[string]any{"scope": "user", "owner": "octo"},
wantKind: "user",
},
{
name: "user write",
args: map[string]any{"scope": "user", "owner": "octo"},
writable: true,
wantErr: true,
},
{
name: "current user",
args: map[string]any{"scope": "current_user"},
wantKind: "current_user",
},
{
name: "missing scope",
args: map[string]any{},
wantErr: true,
},
{
name: "repo missing owner",
args: map[string]any{"scope": "repo", "repo": "demo"},
wantErr: true,
},
{
name: "repo missing repo",
args: map[string]any{"scope": "repo", "owner": "octo"},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
info, err := getProjectScope(tt.args, tt.writable)
if tt.wantErr {
if err == nil {
t.Fatal("expected an error, got nil")
}
return
}
if err != nil {
t.Fatalf("getProjectScope() error = %v", err)
}
if info.kind != tt.wantKind {
t.Fatalf("scope kind = %q, want %q", info.kind, tt.wantKind)
}
})
}
}
func TestProjectReadFn(t *testing.T) {
const (
owner = "octo"
repo = "demo"
projectID = 10
columnID = 20
)
var (
mu sync.Mutex
gotReq = struct {
method string
path string
query string
}{}
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
mu.Lock()
gotReq.method = r.Method
gotReq.path = r.URL.Path
gotReq.query = r.URL.RawQuery
mu.Unlock()
switch r.URL.Path {
case "/api/v1/version":
_, _ = w.Write([]byte(`{"version":"1.28.0"}`))
case fmt.Sprintf("/api/v1/repos/%s/%s/projects", owner, repo):
_, _ = w.Write(fmt.Appendf(nil, `[{"id":%d,"title":"Board","state":"open"}]`, projectID))
case fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d", owner, repo, projectID):
_, _ = w.Write(fmt.Appendf(nil, `{"id":%d,"title":"Board","state":"open"}`, projectID))
case fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns", owner, repo, projectID):
_, _ = w.Write(fmt.Appendf(nil, `[{"id":%d,"title":"Todo","project_id":%d}]`, columnID, projectID))
case fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d/issues", owner, repo, projectID, columnID):
_, _ = w.Write([]byte(`[{"id":5,"number":1,"title":"An issue","state":"open","html_url":"https://example.com/1","user":{"login":"octo"}}]`))
case fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d", owner, repo, projectID, columnID):
_, _ = w.Write(fmt.Appendf(nil, `{"id":%d,"title":"Todo","project_id":%d}`, columnID, projectID))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
origHost, origToken, origVersion := flag.Host, flag.Token, flag.Version
flag.Host, flag.Token, flag.Version = server.URL, "", "test"
defer func() { flag.Host, flag.Token, flag.Version = origHost, origToken, origVersion }()
ctx := context.WithValue(context.Background(), mcpContext.TokenContextKey, "project-read-token")
tests := []struct {
name string
args map[string]any
wantPath string
wantID float64
}{
{
name: "list",
args: map[string]any{
"method": "list",
"scope": "repo",
"owner": owner,
"repo": repo,
"state": "open",
},
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects", owner, repo),
wantID: projectID,
},
{
name: "get",
args: map[string]any{
"method": "get",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
},
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d", owner, repo, projectID),
wantID: projectID,
},
{
name: "list columns",
args: map[string]any{
"method": "list_columns",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
},
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns", owner, repo, projectID),
wantID: columnID,
},
{
name: "get column",
args: map[string]any{
"method": "get_column",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_id": float64(columnID),
},
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d", owner, repo, projectID, columnID),
wantID: columnID,
},
{
name: "list column issues",
args: map[string]any{
"method": "list_column_issues",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_id": float64(columnID),
},
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d/issues", owner, repo, projectID, columnID),
wantID: 5,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := projectReadFn(ctx, tt.args)
if err != nil {
t.Fatalf("projectReadFn() error = %v", err)
}
if result.IsError {
t.Fatalf("projectReadFn() returned error result: %v", result)
}
mu.Lock()
path := gotReq.path
query := gotReq.query
mu.Unlock()
if path != tt.wantPath {
t.Fatalf("request path = %q, want %q", path, tt.wantPath)
}
if tt.name == "list" && query == "" {
t.Fatal("expected list query parameters, got none")
}
if len(result.Content) == 0 {
t.Fatal("expected result content")
}
text, ok := result.Content[0].(*mcp.TextContent)
if !ok {
t.Fatalf("result content type = %T, want text content", result.Content[0])
}
assertFirstID(t, []byte(text.Text), tt.wantID)
})
}
}
func TestProjectWriteFn(t *testing.T) {
const (
owner = "octo"
repo = "demo"
projectID = 10
columnID = 20
issueID = 5
)
type request struct {
method string
path string
body map[string]any
}
var (
mu sync.Mutex
requests []request
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/api/v1/version" {
_, _ = w.Write([]byte(`{"version":"1.28.0"}`))
return
}
var body map[string]any
if r.Body != nil && r.ContentLength > 0 {
_ = json.NewDecoder(r.Body).Decode(&body)
}
mu.Lock()
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: body})
mu.Unlock()
switch r.Method {
case http.MethodGet:
_, _ = w.Write([]byte(`[]`))
case http.MethodPost, http.MethodPatch:
_, _ = w.Write([]byte(`{}`))
default:
w.WriteHeader(http.StatusNoContent)
}
}))
defer server.Close()
origHost, origToken, origVersion := flag.Host, flag.Token, flag.Version
flag.Host, flag.Token, flag.Version = server.URL, "", "test"
defer func() { flag.Host, flag.Token, flag.Version = origHost, origToken, origVersion }()
ctx := context.WithValue(context.Background(), mcpContext.TokenContextKey, "project-write-token")
tests := []struct {
name string
args map[string]any
wantMethod string
wantPath string
wantBody map[string]any
}{
{
name: "create",
args: map[string]any{
"method": "create",
"scope": "repo",
"owner": owner,
"repo": repo,
"title": "Board",
"description": "Project board",
"template_type": "basic_kanban",
"card_type": "images_and_text",
},
wantMethod: http.MethodPost,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects", owner, repo),
wantBody: map[string]any{"title": "Board", "description": "Project board", "template_type": "basic_kanban", "card_type": "images_and_text"},
},
{
name: "update",
args: map[string]any{
"method": "update",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"title": "Updated Board",
"state": "closed",
},
wantMethod: http.MethodPatch,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d", owner, repo, projectID),
wantBody: map[string]any{"title": "Updated Board", "state": "closed"},
},
{
name: "delete",
args: map[string]any{
"method": "delete",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
},
wantMethod: http.MethodDelete,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d", owner, repo, projectID),
},
{
name: "create column",
args: map[string]any{
"method": "create_column",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"title": "Todo",
"color": "#FF0000",
},
wantMethod: http.MethodPost,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns", owner, repo, projectID),
wantBody: map[string]any{"title": "Todo", "color": "#FF0000"},
},
{
name: "update column",
args: map[string]any{
"method": "update_column",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_id": float64(columnID),
"title": "Doing",
"sorting": float64(2),
},
wantMethod: http.MethodPatch,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d", owner, repo, projectID, columnID),
wantBody: map[string]any{"title": "Doing", "sorting": float64(2)},
},
{
name: "delete column",
args: map[string]any{
"method": "delete_column",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_id": float64(columnID),
},
wantMethod: http.MethodDelete,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d", owner, repo, projectID, columnID),
},
{
name: "set default column",
args: map[string]any{
"method": "set_default_column",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_id": float64(columnID),
},
wantMethod: http.MethodPost,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d/default", owner, repo, projectID, columnID),
},
{
name: "move columns",
args: map[string]any{
"method": "move_columns",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_ids": []any{float64(20), float64(21)},
},
wantMethod: http.MethodPost,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/move", owner, repo, projectID),
wantBody: map[string]any{"column_ids": []any{float64(20), float64(21)}},
},
{
name: "add issue",
args: map[string]any{
"method": "add_issue",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_id": float64(columnID),
"issue_id": float64(issueID),
},
wantMethod: http.MethodPost,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d/issues/%d", owner, repo, projectID, columnID, issueID),
},
{
name: "remove issue",
args: map[string]any{
"method": "remove_issue",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"column_id": float64(columnID),
"issue_id": float64(issueID),
},
wantMethod: http.MethodDelete,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/columns/%d/issues/%d", owner, repo, projectID, columnID, issueID),
},
{
name: "move issue",
args: map[string]any{
"method": "move_issue",
"scope": "repo",
"owner": owner,
"repo": repo,
"project_id": float64(projectID),
"issue_id": float64(issueID),
"column_id": float64(columnID),
"sorting": float64(3),
},
wantMethod: http.MethodPost,
wantPath: fmt.Sprintf("/api/v1/repos/%s/%s/projects/%d/issues/%d/move", owner, repo, projectID, issueID),
wantBody: map[string]any{"column_id": float64(columnID), "sorting": float64(3)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := projectWriteFn(ctx, tt.args)
if err != nil {
t.Fatalf("projectWriteFn() error = %v", err)
}
if result.IsError {
t.Fatalf("projectWriteFn() returned error result: %v", result)
}
mu.Lock()
request := requests[len(requests)-1]
mu.Unlock()
if request.method != tt.wantMethod {
t.Fatalf("request method = %q, want %q", request.method, tt.wantMethod)
}
if request.path != tt.wantPath {
t.Fatalf("request path = %q, want %q", request.path, tt.wantPath)
}
if tt.wantBody != nil {
if len(request.body) != len(tt.wantBody) {
t.Fatalf("request body = %v, want %v", request.body, tt.wantBody)
}
for key, want := range tt.wantBody {
if got := request.body[key]; fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("request body[%q] = %v, want %v", key, got, want)
}
}
}
})
}
}
func assertFirstID(t *testing.T, data []byte, want float64) {
t.Helper()
if len(data) > 0 && data[0] == '[' {
var items []map[string]any
if err := json.Unmarshal(data, &items); err != nil {
t.Fatalf("unmarshal result text: %v", err)
}
if len(items) == 0 {
t.Fatal("expected at least one result item")
}
if items[0]["id"] != want {
t.Fatalf("first result id = %v, want %v", items[0]["id"], want)
}
return
}
var item map[string]any
if err := json.Unmarshal(data, &item); err != nil {
t.Fatalf("unmarshal result text: %v", err)
}
if item["id"] != want {
t.Fatalf("result id = %v, want %v", item["id"], want)
}
}
-96
View File
@@ -1,96 +0,0 @@
package project
import (
"gitea.com/gitea/gitea-mcp/pkg/slim"
gitea_sdk "gitea.dev/sdk"
)
func slimProject(p *gitea_sdk.Project) map[string]any {
if p == nil {
return nil
}
return map[string]any{
"id": p.ID,
"title": p.Title,
"description": p.Description,
"state": string(p.State),
"type": string(p.Type),
"template_type": string(p.TemplateType),
"card_type": string(p.CardType),
"owner_id": p.OwnerID,
"repo_id": p.RepoID,
"creator": slim.UserLogin(p.Creator),
"num_open_issues": p.NumOpenIssues,
"num_closed_issues": p.NumClosedIssues,
"num_issues": p.NumIssues,
"html_url": p.HTMLURL,
"created_at": p.Created,
"updated_at": p.Updated,
"closed_at": p.Closed,
}
}
func slimProjects(projects []*gitea_sdk.Project) []map[string]any {
out := make([]map[string]any, 0, len(projects))
for _, p := range projects {
if p == nil {
continue
}
out = append(out, slimProject(p))
}
return out
}
func slimProjectColumn(c *gitea_sdk.ProjectColumn) map[string]any {
if c == nil {
return nil
}
return map[string]any{
"id": c.ID,
"title": c.Title,
"default": c.Default,
"sorting": c.Sorting,
"color": c.Color,
"project_id": c.ProjectID,
"creator": slim.UserLogin(c.Creator),
"created_at": c.Created,
"updated_at": c.Updated,
}
}
func slimProjectColumns(columns []*gitea_sdk.ProjectColumn) []map[string]any {
out := make([]map[string]any, 0, len(columns))
for _, c := range columns {
if c == nil {
continue
}
out = append(out, slimProjectColumn(c))
}
return out
}
func slimProjectIssue(i *gitea_sdk.Issue) map[string]any {
if i == nil {
return nil
}
return map[string]any{
"id": i.ID,
"number": i.Index,
"title": i.Title,
"state": string(i.State),
"html_url": i.HTMLURL,
"user": slim.UserLogin(i.Poster),
}
}
func slimProjectIssues(issues []*gitea_sdk.Issue) []map[string]any {
out := make([]map[string]any, 0, len(issues))
for _, i := range issues {
if i == nil {
continue
}
out = append(out, slimProjectIssue(i))
}
return out
}
+2 -6
View File
@@ -349,10 +349,8 @@ func listRepoPullRequestsFn(ctx context.Context, args map[string]any) (*mcp.Call
State: gitea_sdk.StateType(state), State: gitea_sdk.StateType(state),
Sort: sort, Sort: sort,
Milestone: milestone, Milestone: milestone,
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
@@ -509,10 +507,8 @@ func listPullRequestReviewsFn(ctx context.Context, args map[string]any) (*mcp.Ca
} }
reviews, _, err := client.PullRequests.ListPullReviews(ctx, owner, repo, index, gitea_sdk.ListPullReviewsOptions{ reviews, _, err := client.PullRequests.ListPullReviews(ctx, owner, repo, index, gitea_sdk.ListPullReviewsOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list reviews for %v/%v/pr/%v err: %v", owner, repo, index, err)) return to.ErrorResult(fmt.Errorf("list reviews for %v/%v/pr/%v err: %v", owner, repo, index, err))
@@ -578,7 +574,7 @@ func listPullRequestReviewCommentsFn(ctx context.Context, args map[string]any) (
} else { } else {
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
reviews, _, err := client.PullRequests.ListPullReviews(ctx, owner, repo, index, gitea_sdk.ListPullReviewsOptions{ reviews, _, err := client.PullRequests.ListPullReviews(ctx, owner, repo, index, gitea_sdk.ListPullReviewsOptions{
ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: pageSize}, Page: page, PageSize: pageSize,
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list reviews for %v/%v/pr/%v err: %v", owner, repo, index, err)) return to.ErrorResult(fmt.Errorf("list reviews for %v/%v/pr/%v err: %v", owner, repo, index, err))
@@ -1049,7 +1045,7 @@ func getPullRequestFilesFn(ctx context.Context, args map[string]any) (*mcp.CallT
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err)) return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
} }
files, _, err := client.PullRequests.ListPullRequestFiles(ctx, owner, repo, index, gitea_sdk.ListPullRequestFilesOptions{ files, _, err := client.PullRequests.ListPullRequestFiles(ctx, owner, repo, index, gitea_sdk.ListPullRequestFilesOptions{
ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: pageSize}, Page: page, PageSize: pageSize,
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("get %v/%v/pr/%v files err: %v", owner, repo, index, err)) return to.ErrorResult(fmt.Errorf("get %v/%v/pr/%v files err: %v", owner, repo, index, err))
+49 -2
View File
@@ -2,6 +2,7 @@ package repo
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"gitea.com/gitea/gitea-mcp/pkg/annotation" "gitea.com/gitea/gitea-mcp/pkg/annotation"
@@ -21,6 +22,7 @@ const (
CreateBranchToolName = "create_branch" CreateBranchToolName = "create_branch"
DeleteBranchToolName = "delete_branch" DeleteBranchToolName = "delete_branch"
ListBranchesToolName = "list_branches" ListBranchesToolName = "list_branches"
RenameBranchToolName = "rename_branch"
) )
var ( var (
@@ -52,6 +54,16 @@ var (
tool.Number("page", tool.Description(params.PageDesc), tool.Default(1)), tool.Number("page", tool.Description(params.PageDesc), tool.Default(1)),
tool.Number("per_page", tool.Description(params.PaginationDesc), tool.Default(30)), tool.Number("per_page", tool.Description(params.PaginationDesc), tool.Default(30)),
) )
RenameBranchTool = tool.NewDefinition(
RenameBranchToolName,
"Rename an existing branch in a repository.",
annotation.Write("Rename a branch"),
tool.String("owner", tool.Required(), tool.Description(params.OwnerDesc)),
tool.String("repo", tool.Required(), tool.Description(params.RepoDesc)),
tool.String("branch", tool.Required()),
tool.String("new_name", tool.Required()),
)
) )
func init() { func init() {
@@ -67,6 +79,10 @@ func init() {
Tool: ListBranchesTool, Tool: ListBranchesTool,
Handler: ListBranchesFn, Handler: ListBranchesFn,
}) })
BranchTool.RegisterWrite(tool.ServerTool{
Tool: RenameBranchTool,
Handler: RenameBranchFn,
})
} }
func CreateBranchFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) { func CreateBranchFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
@@ -135,10 +151,8 @@ func ListBranchesFn(ctx context.Context, args map[string]any) (*mcp.CallToolResu
} }
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListRepoBranchesOptions{ opt := gitea_sdk.ListRepoBranchesOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
@@ -151,3 +165,36 @@ func ListBranchesFn(ctx context.Context, args map[string]any) (*mcp.CallToolResu
return to.TextResult(slimBranches(branches)) return to.TextResult(slimBranches(branches))
} }
func RenameBranchFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
owner, err := params.GetString(args, "owner")
if err != nil {
return to.ErrorResult(err)
}
repo, err := params.GetString(args, "repo")
if err != nil {
return to.ErrorResult(err)
}
branch, err := params.GetString(args, "branch")
if err != nil {
return to.ErrorResult(err)
}
newName, err := params.GetString(args, "new_name")
if err != nil {
return to.ErrorResult(err)
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
}
successful, _, err := client.Repositories.RenameRepoBranch(ctx, owner, repo, branch, gitea_sdk.RenameRepoBranchOption{Name: newName})
if err != nil {
return to.ErrorResult(fmt.Errorf("rename branch error: %v", err))
}
if !successful {
return to.ErrorResult(errors.New("rename branch error: unsuccessful"))
}
return to.TextResult("Branch renamed")
}
+136
View File
@@ -0,0 +1,136 @@
package repo
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"gitea.com/gitea/gitea-mcp/pkg/flag"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestRenameBranchFnMissingArgs(t *testing.T) {
fullArgs := map[string]any{
"owner": "octo",
"repo": "demo",
"branch": "old-name",
"new_name": "new-name",
}
for _, missing := range []string{"owner", "repo", "branch", "new_name"} {
t.Run(missing, func(t *testing.T) {
args := map[string]any{}
for k, v := range fullArgs {
if k != missing {
args[k] = v
}
}
result, err := RenameBranchFn(context.Background(), args)
if err != nil {
t.Fatalf("RenameBranchFn() error = %v", err)
}
if !result.IsError {
t.Fatalf("RenameBranchFn() with missing %q, want error result", missing)
}
})
}
}
func TestRenameBranchFn(t *testing.T) {
const (
owner = "octo"
repo = "demo"
branch = "old-name"
newName = "new-name"
)
for _, tc := range []struct {
name string
serverStatus int
wantErr bool
wantContains string
}{
{"success", http.StatusNoContent, false, "Branch renamed"},
{"server error", http.StatusInternalServerError, true, "rename branch error"},
} {
t.Run(tc.name, func(t *testing.T) {
var (
mu sync.Mutex
gotBody map[string]any
)
renamePath := fmt.Sprintf("/api/v1/repos/%s/%s/branches/%s", owner, repo, branch)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/version":
_, _ = w.Write([]byte(`{"version":"1.24.0"}`))
case renamePath:
mu.Lock()
_ = json.NewDecoder(r.Body).Decode(&gotBody)
mu.Unlock()
w.WriteHeader(tc.serverStatus)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
origHost, origToken := flag.Host, flag.Token
flag.Host, flag.Token = server.URL, ""
defer func() { flag.Host, flag.Token = origHost, origToken }()
result, err := RenameBranchFn(context.Background(), map[string]any{
"owner": owner,
"repo": repo,
"branch": branch,
"new_name": newName,
})
if err != nil {
t.Fatalf("RenameBranchFn() error = %v", err)
}
if result.IsError != tc.wantErr {
t.Fatalf("RenameBranchFn() IsError = %v, want %v (result: %v)", result.IsError, tc.wantErr, result)
}
text := result.Content[0].(*mcp.TextContent).Text
if !strings.Contains(text, tc.wantContains) {
t.Fatalf("result = %s, want it to contain %q", text, tc.wantContains)
}
if !tc.wantErr {
mu.Lock()
defer mu.Unlock()
if gotBody["name"] != newName {
t.Fatalf("request body name = %v, want %s", gotBody["name"], newName)
}
}
})
}
}
func TestRenameBranchToolRegistration(t *testing.T) {
found := false
for _, registered := range BranchTool.WriteTools() {
if registered.Tool.Name == RenameBranchToolName {
found = true
break
}
}
if !found {
t.Fatalf("%q is not registered as a write tool", RenameBranchToolName)
}
for _, registered := range BranchTool.ReadTools() {
if registered.Tool.Name == RenameBranchToolName {
t.Fatalf("%q is registered as a read tool, want write only", RenameBranchToolName)
}
}
}
-2
View File
@@ -69,10 +69,8 @@ func ListRepoCommitsFn(ctx context.Context, args map[string]any) (*mcp.CallToolR
sha, _ := args["sha"].(string) sha, _ := args["sha"].(string)
path, _ := args["path"].(string) path, _ := args["path"].(string)
opt := gitea_sdk.ListCommitOptions{ opt := gitea_sdk.ListCommitOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
SHA: sha, SHA: sha,
Path: path, Path: path,
} }
-2
View File
@@ -266,10 +266,8 @@ func DeleteFileFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult
return to.ErrorResult(err) return to.ErrorResult(err)
} }
opt := gitea_sdk.DeleteFileOptions{ opt := gitea_sdk.DeleteFileOptions{
FileOptions: gitea_sdk.FileOptions{
Message: message, Message: message,
BranchName: branchName, BranchName: branchName,
},
SHA: sha, SHA: sha,
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
-2
View File
@@ -236,10 +236,8 @@ func ListReleasesFn(ctx context.Context, args map[string]any) (*mcp.CallToolResu
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err)) return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
} }
releases, _, err := client.Releases.ListReleases(ctx, owner, repo, gitea_sdk.ListReleasesOptions{ releases, _, err := client.Releases.ListReleases(ctx, owner, repo, gitea_sdk.ListReleasesOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
IsDraft: params.GetOptionalBoolPtr(args, "is_draft"), IsDraft: params.GetOptionalBoolPtr(args, "is_draft"),
IsPreRelease: params.GetOptionalBoolPtr(args, "is_pre_release"), IsPreRelease: params.GetOptionalBoolPtr(args, "is_pre_release"),
}) })
-4
View File
@@ -170,10 +170,8 @@ func ForkRepoFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult,
func ListMyReposFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) { func ListMyReposFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListReposOptions{ opt := gitea_sdk.ListReposOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
@@ -194,10 +192,8 @@ func ListOrgReposFn(ctx context.Context, args map[string]any) (*mcp.CallToolResu
} }
page, pageSize := params.GetPagination(args, 100) page, pageSize := params.GetPagination(args, 100)
opt := gitea_sdk.ListOrgReposOptions{ opt := gitea_sdk.ListOrgReposOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
-2
View File
@@ -185,10 +185,8 @@ func ListTagsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult,
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err)) return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
} }
tags, _, err := client.Repositories.ListRepoTags(ctx, owner, repo, gitea_sdk.ListRepoTagsOptions{ tags, _, err := client.Repositories.ListRepoTags(ctx, owner, repo, gitea_sdk.ListRepoTagsOptions{
ListOptions: gitea_sdk.ListOptions{
Page: int(page), Page: int(page),
PageSize: int(pageSize), PageSize: int(pageSize),
},
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list tags error: %v", err)) return to.ErrorResult(fmt.Errorf("list tags error: %v", err))
-2
View File
@@ -54,10 +54,8 @@ func GetRepoTreeFn(ctx context.Context, args map[string]any) (*mcp.CallToolResul
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListTreeOptions{ opt := gitea_sdk.ListTreeOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
Ref: treeSHA, Ref: treeSHA,
Recursive: recursive, Recursive: recursive,
} }
-8
View File
@@ -103,10 +103,8 @@ func UsersFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, err
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.SearchUsersOption{ opt := gitea_sdk.SearchUsersOption{
KeyWord: keyword, KeyWord: keyword,
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
@@ -133,10 +131,8 @@ func OrgTeamsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult,
opt := gitea_sdk.SearchTeamsOptions{ opt := gitea_sdk.SearchTeamsOptions{
Query: query, Query: query,
IncludeDescription: includeDescription, IncludeDescription: includeDescription,
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
@@ -168,10 +164,8 @@ func ReposFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, err
IsArchived: params.GetOptionalBoolPtr(args, "isArchived"), IsArchived: params.GetOptionalBoolPtr(args, "isArchived"),
Sort: sort, Sort: sort,
Order: order, Order: order,
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
@@ -193,10 +187,8 @@ func IssuesFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, er
opt := gitea_sdk.ListIssueOption{ opt := gitea_sdk.ListIssueOption{
KeyWord: query, KeyWord: query,
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
if state, ok := args["state"].(string); ok { if state, ok := args["state"].(string); ok {
opt.State = gitea_sdk.StateType(state) opt.State = gitea_sdk.StateType(state)
-4
View File
@@ -200,10 +200,8 @@ func listTrackedTimesFn(ctx context.Context, args map[string]any) (*mcp.CallTool
} }
times, _, err := client.Issues.ListIssueTrackedTimes(ctx, owner, repo, index, gitea_sdk.ListTrackedTimesOptions{ times, _, err := client.Issues.ListIssueTrackedTimes(ctx, owner, repo, index, gitea_sdk.ListTrackedTimesOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list tracked times for %s/%s#%d err: %v", owner, repo, index, err)) return to.ErrorResult(fmt.Errorf("list tracked times for %s/%s#%d err: %v", owner, repo, index, err))
@@ -290,10 +288,8 @@ func listRepoTimesFn(ctx context.Context, args map[string]any) (*mcp.CallToolRes
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err)) return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
} }
times, _, err := client.Issues.ListRepoTrackedTimes(ctx, owner, repo, gitea_sdk.ListTrackedTimesOptions{ times, _, err := client.Issues.ListRepoTrackedTimes(ctx, owner, repo, gitea_sdk.ListTrackedTimesOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
}) })
if err != nil { if err != nil {
return to.ErrorResult(fmt.Errorf("list repo tracked times for %s/%s err: %v", owner, repo, err)) return to.ErrorResult(fmt.Errorf("list repo tracked times for %s/%s err: %v", owner, repo, err))
-2
View File
@@ -59,10 +59,8 @@ func GetUserOrgsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResul
page, pageSize := params.GetPagination(args, 30) page, pageSize := params.GetPagination(args, 30)
opt := gitea_sdk.ListOrgsOptions{ opt := gitea_sdk.ListOrgsOptions{
ListOptions: gitea_sdk.ListOptions{
Page: page, Page: page,
PageSize: pageSize, PageSize: pageSize,
},
} }
client, err := gitea.ClientFromContext(ctx) client, err := gitea.ClientFromContext(ctx)
if err != nil { if err != nil {
+1 -2
View File
@@ -191,8 +191,7 @@ func TestDownloadAttachmentErrorsOnNon2xx(t *testing.T) {
if status != http.StatusForbidden { if status != http.StatusForbidden {
t.Fatalf("status = %d, want %d", status, http.StatusForbidden) t.Fatalf("status = %d, want %d", status, http.StatusForbidden)
} }
var httpErr *HTTPError if _, ok := errors.AsType[*HTTPError](err); !ok {
if !errors.As(err, &httpErr) {
t.Fatalf("expected HTTPError, got %T", err) t.Fatalf("expected HTTPError, got %T", err)
} }
} }
+1 -2
View File
@@ -236,8 +236,7 @@ func OpenAttachment(ctx context.Context, attachmentPath, accept string) (*Attach
func DownloadAttachment(ctx context.Context, attachmentPath, accept string) ([]byte, string, int, error) { func DownloadAttachment(ctx context.Context, attachmentPath, accept string) ([]byte, string, int, error) {
resp, err := OpenAttachment(ctx, attachmentPath, accept) resp, err := OpenAttachment(ctx, attachmentPath, accept)
if err != nil { if err != nil {
var httpErr *HTTPError if httpErr, ok := errors.AsType[*HTTPError](err); ok {
if errors.As(err, &httpErr) {
return nil, "", httpErr.StatusCode, err return nil, "", httpErr.StatusCode, err
} }
return nil, "", 0, err return nil, "", 0, err
+1 -2
View File
@@ -102,8 +102,7 @@ func (s ServerTool) MCPHandler() mcp.ToolHandler {
result, err = s.Handler(ctx, arguments) result, err = s.Handler(ctx, arguments)
if err != nil { if err != nil {
var protocolErr *jsonrpc.Error if _, ok := errors.AsType[*jsonrpc.Error](err); ok {
if errors.As(err, &protocolErr) {
return nil, err return nil, err
} }
return to.ErrorResult(err) return to.ErrorResult(err)
-96
View File
@@ -1,96 +0,0 @@
#!/bin/sh
# Copyright 2026 The Gitea Authors. All rights reserved.
# SPDX-License-Identifier: MIT
#
# upload-r2.sh uploads a single local file to a single object key in a
# Cloudflare R2 bucket, using curl's built-in AWS SigV4 signer (R2 is
# S3-API compatible).
#
# Usage:
# upload-r2.sh <local-file> <remote-key>
# upload-r2.sh --check-config
#
# The second form only validates that the required environment
# variables below are set (it does not touch the network), and is
# meant to be run as an early preflight step in CI so that a missing
# R2_* secret is reported before anything is built or published.
#
# Required environment variables:
# R2_ENDPOINT Base URL of the R2 endpoint, e.g.
# https://<account>.r2.cloudflarestorage.com
# R2_BUCKET Destination bucket name.
# R2_ACCESS_KEY_ID R2 access key id.
# R2_SECRET_ACCESS_KEY R2 secret access key.
set -eu
# check_env validates that all required R2_* environment variables are
# set and non-empty, so the validation logic only exists in one place
# for both the normal upload mode and --check-config.
check_env() {
missing=""
if [ -z "${R2_ENDPOINT:-}" ]; then
missing="$missing R2_ENDPOINT"
fi
if [ -z "${R2_BUCKET:-}" ]; then
missing="$missing R2_BUCKET"
fi
if [ -z "${R2_ACCESS_KEY_ID:-}" ]; then
missing="$missing R2_ACCESS_KEY_ID"
fi
if [ -z "${R2_SECRET_ACCESS_KEY:-}" ]; then
missing="$missing R2_SECRET_ACCESS_KEY"
fi
if [ -n "$missing" ]; then
echo "upload-r2.sh: missing required environment variable(s):$missing" >&2
exit 1
fi
}
if [ "$#" -eq 1 ] && [ "$1" = "--check-config" ]; then
check_env
echo "upload-r2.sh: R2 configuration OK"
exit 0
fi
if [ "$#" -ne 2 ]; then
echo "usage: upload-r2.sh <local-file> <remote-key>" >&2
echo " upload-r2.sh --check-config" >&2
exit 1
fi
local_file="$1"
remote_key="$2"
if [ ! -f "$local_file" ]; then
echo "upload-r2.sh: local file not found: $local_file" >&2
exit 1
fi
check_env
# Strip a single trailing slash from the endpoint, if present, so that
# building the path-style URL below never produces a double slash.
endpoint="${R2_ENDPOINT%/}"
url="$endpoint/$R2_BUCKET/$remote_key"
# Credentials are passed to curl through a config file read from
# stdin rather than as a command-line argument, so they never show up
# in `ps` output.
#
# --fail-with-body (instead of plain --fail) still exits non-zero on
# HTTP errors, but also prints R2's XML error body, which is where the
# actual error code lives (SignatureDoesNotMatch, NoSuchBucket,
# AccessDenied, ...). --retry 3 (without --retry-all-errors) only
# retries the transient cases (5xx, 408, 429, connection failures).
printf 'user = "%s:%s"\n' "$R2_ACCESS_KEY_ID" "$R2_SECRET_ACCESS_KEY" | curl \
--config - \
--fail-with-body \
--silent \
--show-error \
--retry 3 \
--aws-sigv4 "aws:amz:auto:s3" \
--upload-file "$local_file" \
"$url"