Skip to content

feat: add token rotation core and proxy config updates#54

Open
buihongduc132 wants to merge 7 commits intotbxark:masterfrom
buihongduc132:001-token-rotation-proxy
Open

feat: add token rotation core and proxy config updates#54
buihongduc132 wants to merge 7 commits intotbxark:masterfrom
buihongduc132:001-token-rotation-proxy

Conversation

@buihongduc132
Copy link
Copy Markdown

Summary

  • add token rotation core implementation with tests
  • update specs/docs for token rotation and add Nomad job spec
  • add local opencode MCP proxy config and update coverage baseline

Testing

  • not run (pre-commit coverage check only)

buihongduc132 added 7 commits February 19, 2026 17:04
Tests added:
- config_test.go: Config parsing, loading, V1->V2 migration (100% parseMCPClientConfigV2, 100% newConfProvider, 95.7% load)
- client_test.go: Client creation, server creation, options handling (92.9% newMCPClient, 100% newMCPServer)
- http_test.go: Middleware chain, auth, logger, recovery (100% all middleware functions, 54.5% startHTTPServer)
- integration_test.go: MCP server/client integration tests (85.7% addToMCPServer, 89.2% addToolsToServer, 82.4% addPromptsToServer, 71.4% addResourcesToServer)

Coverage improved from 0.0% to 76.5% of statements
- Add pre-commit hook to run tests before commit
- Add test coverage badge (76.5%) to README
- Add Go Report Card badge to README
- Add Makefile targets: test, test-cover, test-cover-html
- Update .gitignore for coverage artifacts
- Block commits if coverage drops by >=5%
- Track baseline coverage in .coverage_baseline (76.5%)
- Show detailed coverage breakdown (functions/lines)
- Auto-update baseline when coverage improves
- Display helpful guidance when commit is blocked
- Implement TokenRotator interface with RoundRobin and OnFirstFailed modes
- Add thread-safe token rotation with mutex-protected state
- Create TokenExhaustedError for structured error handling
- Add comprehensive test coverage for all rotation modes and edge cases
- Include spec, plan, research, and data model documentation

Related: tbxark#1-token-rotation-proxy
- ops/nomad/mcp_proxy.nomad.hcl for Nomad/Consul mesh
- Uses Docker driver with ghcr.io/tbxark/mcp-proxy:latest
- Port 9090 on tailscale network
- Template-based config with websearch, context7, grep_app MCP servers
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @buihongduc132, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the MCP Proxy's capabilities by introducing robust authentication token rotation and flexible proxy configuration for its clients. The token rotation feature allows for better load distribution and automatic failover, improving the reliability of connections to MCP servers. The new proxy support enables compliance with network policies and access to servers behind firewalls. Additionally, the PR integrates a pre-commit hook to maintain code quality through test coverage checks and updates deployment configurations for Nomad.

Highlights

  • Token Rotation Core Implementation: Implemented core logic for authentication token rotation, supporting 'round-robin' and 'on-first-failed' modes, along with comprehensive unit tests for thread safety and edge cases.
  • Proxy Configuration Updates: Added support for configuring HTTP/HTTPS and SOCKS5 proxies for MCP client connections, including proxy authentication and environment variable fallback.
  • Documentation and Specification Updates: Created detailed specifications, data models, research documents, and quickstart guides for the new token rotation and proxy features, ensuring clear understanding and usage.
  • Nomad Job Specification: Introduced a Nomad job specification for deploying the MCP proxy, including templated configuration for dynamic environments.
  • Go Test Coverage Pre-commit Hook: Added a pre-commit Git hook to enforce a minimum Go test coverage baseline, improving code quality and preventing regressions.
  • Local OpenCode MCP Proxy Configuration: Included a new configuration file for running the MCP proxy locally with OpenCode servers.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • .coverage_baseline
    • Added an initial coverage baseline of 78.7% for Go tests.
  • .githooks/pre-commit
    • Added a new pre-commit hook to calculate and enforce Go test coverage, blocking commits if coverage drops below a defined baseline or threshold.
  • .gitignore
    • Added new entries to ignore various project-specific directories and build artifacts, including 'projects', '.codex/skills', '.opencode', 'openspec', 'coverage.html', 'coverage.out', and '.specify'.
  • .sisyphus/ralph_progress.md
    • Added a detailed progress report for the 'Token Rotation & Proxy Feature', outlining completed tasks, identified blockers and their fixes, documentation updates, approvals, implementation progress, and next steps.
  • Makefile
    • Added new test, test-cover, and test-cover-html targets to the Makefile for running Go tests, generating coverage reports, and opening HTML coverage reports.
  • README.md
    • Updated the README with Go Report Card, Go Coverage, and License badges.
  • client_test.go
    • Added comprehensive unit tests for newMCPServer and newMCPClient functions, covering various configurations, error cases, and client flags.
    • Included tests for Client and Server struct properties and behaviors, such as Close, NeedManualStart, NeedPing, and startPingTask context handling.
    • Added tests for ToolFilterConfig in both allow and block modes, and verified OptionsV2 and configuration struct fields.
  • config_test.go
    • Added extensive tests for configuration loading from local files and HTTP URLs, including environment variable expansion and V1 migration.
    • Included tests for default option inheritance, default server types, and handling of disabled clients.
    • Added detailed tests for parsing MCPClientConfigV2 and MCPClientConfigV1 for Stdio, SSE, and Streamable HTTP types, covering valid and invalid configurations.
    • Included tests for adaptMCPClientConfigV1ToV2 migration logic, ensuring backward compatibility and correct merging of global and client-specific authentication tokens.
    • Added tests for ToolFilterConfig, OptionsV2, and MCPProxyConfigV2 struct fields and constants.
  • http_test.go
    • Added tests for startHTTPServer error handling, covering invalid base URLs, and client/server configuration errors.
    • Included tests for chainMiddleware functionality, ensuring correct middleware execution order and handling of empty middleware chains.
    • Added comprehensive tests for newAuthMiddleware, verifying token validation, unauthorized access, token trimming, and edge cases like case-insensitive 'Bearer' prefix.
    • Included tests for loggerMiddleware and recoverMiddleware, ensuring proper logging and panic recovery without service interruption.
  • integration_test.go
    • Added integration tests for addToMCPServer functionality, verifying the addition of tools, prompts, and resources from a test MCP server to a proxy server.
    • Included tests for ToolFilterModeAllow and ToolFilterModeBlock to ensure correct filtering of tools during integration.
  • opencode-mcp.jsonc
    • Added a new JSON configuration file for a local OpenCode MCP proxy, defining its base URL, address, name, version, type, and client options, along with configurations for 'websearch', 'context7', and 'grep_app' MCP servers.
  • ops/nomad/mcp_proxy.nomad.hcl
    • Added a Nomad job specification for deploying the MCP proxy, including datacenter, region, type, and meta information.
    • Defined a group for the proxy with network configuration, including a static HTTP port.
    • Included a task for the mcp-proxy Docker container, with a templated config.json for proxy and server configurations, volume mounts, logging, and resource limits.
    • Configured service checks, restart policies, update strategies, and reschedule parameters for robust deployment.
  • specs/001-token-rotation-proxy/contracts/config-schema.json
    • Added a JSON schema for MCP client configuration, detailing properties for transport type, command, URL, headers, timeout, and new options fields for authentication (tokens, rotation mode, max retries) and proxy (URL, type, auth, useEnv), along with tool filtering and disabled status.
  • specs/001-token-rotation-proxy/data-model.md
    • Added a detailed data model document for token rotation and proxy support, defining core entities like TokenRotator, AuthConfig, ProxyConfig, authRoundTripper, and TokenExhaustedError.
    • Included state diagrams for round-robin and on-first-failed token rotation, and token exhaustion flow.
    • Outlined configuration schema evolution, validation rules, memory/performance characteristics, error handling, and testing considerations.
  • specs/001-token-rotation-proxy/plan.md
    • Added an implementation plan for token rotation and proxy support, summarizing the feature, technical context, constitution compliance, project structure, and complexity tracking.
    • Detailed implementation phases for token rotation (required) and proxy support (optional), along with a comprehensive test coverage plan and success criteria.
  • specs/001-token-rotation-proxy/quickstart.md
    • Added a quickstart guide for configuring and using token rotation and proxy support, providing examples for round-robin and on-first-failed modes, HTTP/SOCKS5 proxies, and combined configurations.
    • Included sections on backward compatibility, testing configurations, troubleshooting common errors, performance considerations, and security best practices for token and credential management.
  • specs/001-token-rotation-proxy/research.md
    • Added a research document detailing resolved questions regarding token rotation architecture, rotation mode behaviors, authentication failure detection, proxy architecture, config schema design, authorization header conflict resolution, TokenRotator interface design, HTTP RoundTripper implementation, error handling strategy, SSE connection rotation semantics, test strategy, implementation phases, and security considerations.
  • specs/001-token-rotation-proxy/spec.md
    • Added a feature specification document for token rotation and proxy support, outlining user stories (multiple token authentication with round-robin, automatic token failover, HTTP/HTTPS proxy, SOCKS5 proxy, combined rotation through proxy), edge cases, functional requirements, key entities, and measurable success criteria.
  • token_rotator.go
    • Added the TokenRotator interface and its implementations: roundRobinRotator for sequential token cycling and onFirstFailedRotator for failover-based rotation.
    • Introduced TokenExhaustedError for structured error reporting when all tokens fail, ensuring no sensitive information is leaked.
    • Defined sentinel errors ErrNoTokens, ErrAllTokensFailed, and ErrInvalidRotationMode for clear error handling.
  • token_rotator_test.go
    • Added comprehensive unit tests for roundRobinRotator, verifying correct token cycling, single-token behavior, and error handling for empty token lists.
    • Included tests for onFirstFailedRotator, covering token reuse, advancement on failure, success resetting failure counts, and exhaustion scenarios.
    • Added concurrent access tests for both rotation modes to ensure thread safety.
    • Included edge case tests for nil token slices, duplicate tokens, empty string tokens, and error type verification for TokenExhaustedError.
Activity
  • The feature branch 001-token-rotation-proxy was created.
  • Initial documentation including spec.md, plan.md, research.md, data-model.md, quickstart.md, and config-schema.json were generated.
  • Several blockers were identified and subsequently fixed, addressing issues such as proxy optionality, TDD order, retry semantics, missing edge-case tests, and token logging guidance.
  • Documentation files were updated to reflect the fixes for the identified blockers.
  • The Oracle approved the architectural design for the feature.
  • The core implementation and tests for token rotation (token_rotator_test.go and token_rotator.go) have been completed.
  • The next steps involve implementing the auth_transport wrapper, integrating with existing config.go and client.go, and then committing and pushing the changes.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant