gitea-mcp: 初次落地 Gitea MCP Server (.NET 10, V1 only-read)
把 Gitea (git.zhengchentao.win) 通过 MCP 暴露给 Claude.ai:列 repo、读代码、看 commits / issues / PR / orgs / packages / actions。 设计文档见 vault Coding/gitea-mcp/gitea-mcp 设计.md。 代码模板复用 obsidian-mcp(.NET 10 + ModelContextProtocol SDK + JwtBearer)。 19 个只读 Tool(全部 scope=read:gitea): Repo / 文件: - list_repos / read_repo - list_tree(max_entries=500 防爆) - read_file(max_bytes=1MB,超出 truncated=true) - search_code(走 /repos/search-code,indexer 未启用时返回结构化错误说明) 分支 / 提交: - list_branches / list_commits / read_commit(diff 文件数限 50) Issue / PR: - list_issues / read_issue(含评论) - list_pulls / read_pull(含评论 + 改动文件列表) Org / Package(用户额外授权 read:organization + read:package): - list_orgs / read_org - list_packages / read_package Gitea Actions(运维友好): - list_workflow_runs / read_run_log 技术栈: - .NET 10 + ModelContextProtocol SDK 1.0 - HttpClientFactory + Microsoft.Extensions.Http.Resilience(指数 backoff,5xx/429/网络错误重试) - JwtBearer (HS256, Current+Previous fallback, MapInboundClaims=false) - aud=gitea, scope=read:gitea, iss=https://auth.zhengchentao.win Gitea API client: - Authorization: token <PAT> (admin PAT,仅 read scope) - BaseUrl=https://git.zhengchentao.win - 错误映射:401/403 → UnauthorizedAccessException,404 → KeyNotFoundException,5xx → InvalidOperationException - RepoBlacklist 黑名单(owner/repo 精确匹配,默认空) 部署: - Dockerfile multi-stage,COPY --chown,non-root user - .gitea/workflows/build-image.yml:build + deploy 双 job,buildkit v0.13.2 - 容器内 :8080,宿主端口 9092 - 子域名 git-mcp.zhengchentao.win(区别于 Gitea 本体 git.zhengchentao.win) 测试:6/6 单测过(GiteaRepoFilter 黑名单匹配) Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
+85
@@ -0,0 +1,85 @@
|
||||
using GiteaMcp.Auth;
|
||||
using GiteaMcp.Config;
|
||||
using GiteaMcp.Endpoints;
|
||||
using GiteaMcp.Services;
|
||||
using Microsoft.Extensions.Http.Resilience;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// ─── 配置绑定 ───────────────────────────────────────────────
|
||||
builder.Services.Configure<GiteaOptions>(
|
||||
builder.Configuration.GetSection(GiteaOptions.SectionName));
|
||||
builder.Services.Configure<JwtOptions>(
|
||||
builder.Configuration.GetSection(JwtOptions.SectionName));
|
||||
builder.Services.Configure<McpDiscoveryOptions>(
|
||||
builder.Configuration.GetSection(McpDiscoveryOptions.SectionName));
|
||||
|
||||
// ─── JWT Bearer + Scope Policy ─────────────────────────────
|
||||
builder.Services.AddGiteaJwtBearer(builder.Configuration);
|
||||
builder.Services.AddScopePolicies();
|
||||
|
||||
// ─── HTTP Context Accessor(Tool 里可选用,暂保留接口) ────────
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
|
||||
// ─── Gitea HTTP Client ─────────────────────────────────────
|
||||
var giteaBaseUrl = builder.Configuration["Gitea:BaseUrl"]
|
||||
?? "https://git.zhengchentao.win";
|
||||
var giteaPat = builder.Configuration["Gitea:AdminPat"] ?? string.Empty;
|
||||
|
||||
builder.Services.AddHttpClient("gitea", client =>
|
||||
{
|
||||
// 确保 BaseAddress 末尾有斜杠(HttpClient 的规范)
|
||||
var url = giteaBaseUrl.TrimEnd('/') + "/";
|
||||
client.BaseAddress = new Uri(url);
|
||||
|
||||
// Gitea 推荐 "token <PAT>" 格式,比 Bearer 更稳
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("token", giteaPat);
|
||||
|
||||
client.DefaultRequestHeaders.Accept.Add(
|
||||
new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// 单请求超时 30s
|
||||
client.Timeout = TimeSpan.FromSeconds(30);
|
||||
})
|
||||
.AddStandardResilienceHandler(options =>
|
||||
{
|
||||
// 3 次重试,指数退避(Microsoft.Extensions.Http.Resilience 标准配置)
|
||||
options.Retry.MaxRetryAttempts = 3;
|
||||
options.Retry.BackoffType = Polly.DelayBackoffType.Exponential;
|
||||
options.Retry.Delay = TimeSpan.FromSeconds(1);
|
||||
options.Retry.UseJitter = true;
|
||||
// 仅对 5xx / 429 / 网络错误重试;4xx 由 ShouldHandle 默认配置自动跳过
|
||||
options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(90);
|
||||
options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(30);
|
||||
});
|
||||
|
||||
// ─── 业务服务 ──────────────────────────────────────────────
|
||||
builder.Services.AddSingleton<GiteaRepoFilter>();
|
||||
builder.Services.AddScoped<GiteaApiClient>();
|
||||
|
||||
// ─── MCP Server ────────────────────────────────────────────
|
||||
builder.Services.AddMcpServer()
|
||||
.WithHttpTransport() // Streamable HTTP(Claude.ai custom connector 走这个)
|
||||
.WithToolsFromAssembly(); // 自动扫描 [McpServerToolType]
|
||||
|
||||
// ─── Build ─────────────────────────────────────────────────
|
||||
var app = builder.Build();
|
||||
|
||||
// ─── Middleware 顺序:认证 → 授权 → 路由 ────────────────────
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// ─── Endpoints ─────────────────────────────────────────────
|
||||
app.MapDiscovery();
|
||||
|
||||
// MCP 端点:要求通过 JWT 认证 + read:gitea scope
|
||||
app.MapMcp("/mcp")
|
||||
.RequireAuthorization(ScopePolicies.ReadGitea);
|
||||
|
||||
// 健康检查(Kubernetes / Docker healthcheck 用)
|
||||
app.MapGet("/healthz", () => Results.Ok(new { status = "ok", timestamp = DateTimeOffset.UtcNow }));
|
||||
|
||||
app.Run();
|
||||
Reference in New Issue
Block a user