{"id":46507017,"url":"https://github.com/hiddenpath/spiderswitch","last_synced_at":"2026-03-08T19:02:02.216Z","repository":{"id":341411452,"uuid":"1169573634","full_name":"hiddenpath/spiderswitch","owner":"hiddenpath","description":"MCP server for dynamic AI model switching in the ai-lib ecosystem. MCP服务器，用于ai-lib生态系统动态AI模型切换。","archived":false,"fork":false,"pushed_at":"2026-03-02T09:54:27.000Z","size":109,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-02T12:27:12.569Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hiddenpath.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-28T22:14:40.000Z","updated_at":"2026-03-02T09:54:32.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/hiddenpath/spiderswitch","commit_stats":null,"previous_names":["hiddenpath/ai-mcp-model-switcher","hiddenpath/spiderswitch"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/hiddenpath/spiderswitch","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hiddenpath%2Fspiderswitch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hiddenpath%2Fspiderswitch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hiddenpath%2Fspiderswitch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hiddenpath%2Fspiderswitch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hiddenpath","download_url":"https://codeload.github.com/hiddenpath/spiderswitch/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hiddenpath%2Fspiderswitch/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30182687,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-06T14:42:24.748Z","status":"ssl_error","status_checked_at":"2026-03-06T14:42:14.925Z","response_time":250,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-03-06T15:04:28.477Z","updated_at":"2026-03-08T19:02:02.202Z","avatar_url":"https://github.com/hiddenpath.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# spiderswitch for ai-lib Ecosystem\n\n[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)\n[![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-green.svg)](LICENSE)\n\nMCP (Model Context Protocol) server that enables agents to dynamically switch AI models from the [ai-lib ecosystem](https://github.com/hiddenpath/ai-lib-python).\n\n## Features\n\n- **Protocol-Driven**: All model configurations loaded from ai-protocol manifests (ARCH-001)\n- **Multi-Provider Support**: Switch between OpenAI, Anthropic, Google, DeepSeek, and more\n- **Runtime-Agnostic**: Uses ai-lib-python SDK for unified model interaction\n- **MCP-Compliant**: Implements standard MCP tools over stdio transport\n- **Capability Discovery**: Query available models and their capabilities\n- **Runtime Profile Signal**: Exposes runtime capability profile for upper-layer routing policy engines\n- **Local Readiness Hints**: `list_models` includes API key presence and proxy readiness per provider\n- **Explicit Exit Path**: `exit_switcher` resets switcher runtime/state for clean fallback\n- **Auto Protocol Setup**: Auto-detects local `ai-protocol` path and sets `AI_PROTOCOL_PATH` for current process\n- **Official Dist Sync**: Best-effort sync of official `dist/v1/*.json` snapshot into local `ai-protocol/dist/v1`\n\n## Quick Start\n\n### Installation\n\n```bash\n# Clone the repository\ngit clone https://github.com/hiddenpath/spiderswitch.git\ncd spiderswitch\n\n# Install dependencies\npip install -e .\n```\n\n### Environment Setup\n\nSet up your API keys:\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"\nexport ANTHROPIC_API_KEY=\"sk-ant-...\"\nexport GOOGLE_API_KEY=\"...\"\n```\n\nRecommended provider key mapping:\n\n| Provider | Environment Variable |\n|----------|----------------------|\n| openai | `OPENAI_API_KEY` |\n| anthropic | `ANTHROPIC_API_KEY` |\n| google | `GOOGLE_API_KEY` or `GEMINI_API_KEY` |\n| deepseek | `DEEPSEEK_API_KEY` |\n| cohere | `COHERE_API_KEY` |\n| mistral | `MISTRAL_API_KEY` |\n\nSecurity note:\n- Prefer environment variables over passing `api_key` in tool arguments.\n- The server redacts sensitive fields in logs, but passing secrets in arguments still increases exposure risk in client traces.\n\nOptional runtime env controls:\n- `SPIDERSWITCH_SYNC_DIST=0` to disable startup sync of official `dist` json files.\n- `AI_PROTOCOL_DIST_BASE_URL` to override raw dist source (default official GitHub raw URL).\n- `AI_PROTOCOL_DIST_API_BASE_URL` to override GitHub API listing source for models/providers dist json.\n\n### Configuration\n\nAdd to your MCP client configuration (e.g., Cursor, Claude Desktop):\n\n```json\n{\n  \"mcpServers\": {\n    \"spiderswitch\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"spiderswitch.server\"],\n      \"env\": {\n        \"AI_PROTOCOL_PATH\": \"/path/to/ai-protocol\"\n      }\n    }\n  }\n}\n```\n\n### Usage\n\nIn your agent, call MCP tools:\n\n```python\n# List available models\nmodels = await mcp_client.call_tool(\"list_models\", {})\n\n# Switch to Claude 3.5 Sonnet\nawait mcp_client.call_tool(\n    \"switch_model\",\n    {\"model\": \"anthropic/claude-3-5-sonnet\"}\n)\n\n# Check current status\nstatus = await mcp_client.call_tool(\"get_status\", {})\n```\n\n## Available MCP Tools\n\n### 1. switch_model\n\nSwitches to a different AI model/provider.\n\n**Parameters:**\n- `model` (string, required): Model identifier (e.g., `openai/gpt-4o`, `anthropic/claude-3-5-sonnet`)\n- `api_key` (string, optional): Explicit API key (overrides environment variable; not recommended for production)\n- `base_url` (string, optional): Custom base URL for testing/mock\n- `runtime_id` (string, optional): Runtime target selected by upper-layer policy\n\n**Returns:**\n```json\n{\n  \"status\": \"success\",\n  \"data\": {\n    \"id\": \"anthropic/claude-3-5-sonnet\",\n    \"provider\": \"anthropic\",\n    \"capabilities\": [\"streaming\", \"tools\", \"vision\"],\n    \"proxy_status\": {\n      \"provider\": \"anthropic\",\n      \"proxy_required_guess\": false,\n      \"proxy_configured\": false,\n      \"configured_proxy_env_vars\": [],\n      \"hint\": null\n    },\n    \"warnings\": []\n  },\n  \"message\": \"Successfully switched to anthropic/claude-3-5-sonnet\"\n}\n```\n\n### 2. list_models\n\nLists all available models from registered providers.\n\n**Parameters:**\n- `filter_provider` (string, optional): Filter by provider ID\n- `filter_capability` (string, optional): Filter by capability (`streaming`, `tools`, `vision`, `embeddings`, `audio`)\n- `runtime_id` (string, optional): Runtime target selected by upper-layer policy\n\n**Returns:**\n```json\n{\n  \"status\": \"success\",\n  \"data\": {\n    \"count\": 2,\n    \"runtime_profile\": {\n      \"runtime_id\": \"python-runtime\",\n      \"language\": \"python\",\n      \"supports\": [\"model_switching\", \"capability_filtering\", \"provider_manifest_loading\"]\n    },\n    \"models\": [\n      {\n        \"id\": \"openai/gpt-4o\",\n        \"provider\": \"openai\",\n        \"capabilities\": [\"streaming\", \"tools\", \"vision\"],\n        \"api_key_status\": {\n          \"provider\": \"openai\",\n          \"has_api_key\": true,\n          \"expected_env_vars\": [\"OPENAI_API_KEY\"],\n          \"configured_env_vars\": [\"OPENAI_API_KEY\"]\n        },\n        \"proxy_status\": {\n          \"provider\": \"openai\",\n          \"proxy_required_guess\": true,\n          \"proxy_configured\": false,\n          \"configured_proxy_env_vars\": [],\n          \"hint\": \"This provider may require proxy access in your network region. Set HTTPS_PROXY/HTTP_PROXY in the MCP server process environment if needed.\"\n        }\n      },\n      {\n        \"id\": \"anthropic/claude-3-5-sonnet\",\n        \"provider\": \"anthropic\",\n        \"capabilities\": [\"streaming\", \"tools\", \"vision\"]\n      }\n    ],\n    \"filtered\": {\n      \"require_api_key\": false,\n      \"provider\": null,\n      \"capability\": null\n    }\n  }\n}\n```\n\n### 3. get_status\n\nGets current model status and configuration.\n\n**Parameters:**\n- `runtime_id` (string, optional): Query status in a specific runtime scope\n\n**Returns:**\n```json\n{\n  \"status\": \"success\",\n  \"data\": {\n    \"provider\": \"anthropic\",\n    \"model\": \"claude-3-5-sonnet\",\n    \"capabilities\": [\"streaming\", \"tools\", \"vision\"],\n    \"runtime_profile\": {\n      \"runtime_id\": \"python-runtime\",\n      \"language\": \"python\",\n      \"supports\": [\"model_switching\", \"capability_filtering\", \"provider_manifest_loading\"]\n    },\n    \"is_configured\": true,\n    \"connection_epoch\": 3,\n    \"last_switched_at\": \"2026-03-02T09:00:00+00:00\"\n  }\n}\n```\n\n### 4. exit_switcher\n\nExplicitly reset spiderswitch state and runtime client.\n\n**Parameters:**\n- `runtime_id` (string, optional): Runtime id for scoped reset\n- `scope` (string, optional): `all` (default) or `runtime`\n\n**Returns:**\n```json\n{\n  \"status\": \"success\",\n  \"data\": {\n    \"exited\": true,\n    \"status\": {\n      \"provider\": null,\n      \"model\": null,\n      \"is_configured\": false\n    }\n  }\n}\n```\n\n## API Key Guidance and Troubleshooting\n\nWhen `switch_model` fails due to missing credentials, the response includes:\n- `provider`: which provider is missing credentials\n- `expected_env_vars`: accepted environment variable names\n- `hint`: actionable setup instruction\n\nTypical setup flow:\n1. Configure provider key in your MCP server process environment.\n2. Restart the MCP server process if your client does not support hot env reload.\n3. Call `switch_model`.\n4. Verify with `get_status`.\n\n## Connection Coordination with Agent Runtime\n\nThis MCP server manages model client lifecycle internally. To avoid conflicts with an agent's own connection manager:\n- Treat MCP switcher as the control plane for model selection.\n- Let the agent side observe `get_status.connection_epoch`.\n- Rebuild agent-side cached sessions only when `connection_epoch` increases.\n\nThis pattern prevents stale session reuse after model switches and supports deterministic synchronization.\n\n## Runtime Routing Boundary\n\nspiderswitch only executes routing actions with explicit runtime signals:\n\n- Runtime capability model is exposed via `runtime_profile` (runtime-neutral schema).\n- Runtime selection policy remains in upper-layer applications.\n- Built-in registry/resolver only resolves `runtime_id` and does not implement cost/quality/business strategy.\n\n## Architecture\n\n```\nspiderswitch/\n├── src/\n│   ├── server.py           # MCP server main entry point\n│   ├── tools/              # MCP tool implementations\n│   │   ├── switch.py       # switch_model tool\n│   │   ├── list.py         # list_models tool\n│   │   ├── status.py       # get_status tool\n│   │   └── reset.py        # exit_switcher tool\n│   ├── runtime/            # Runtime abstraction layer\n│   │   ├── base.py         # Base runtime interface\n│   │   ├── python_runtime.py  # ai-lib-python implementation\n│   │   └── loader.py       # ProtocolLoader wrapper\n│   └── state.py            # State management\n├── tests/                  # Test suite\n└── pyproject.toml          # Project configuration\n```\n\n## Development\n\n### Running Tests\n\n```bash\n# Install test dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run with coverage\npytest --cov=src/spiderswitch\n```\n\n### Testing with Mock Server\n\nUse [ai-protocol-mock](https://github.com/hiddenpath/ai-protocol-mock):\n\n```bash\n# Start mock server\ndocker-compose up -d ai-protocol-mock\n\n# Run with mock\nMOCK_HTTP_URL=http://localhost:4010 python -m spiderswitch.server\n```\n\n### Code Style\n\n```bash\n# Format code\nruff format src tests\n\n# Lint\nruff check src tests\n\n# Type check\nmypy src\n```\n\n## Protocol-Driven Design (ARCH-001)\n\nThis server follows the ai-lib design principle:\n\n\u003e **一切逻辑皆算子，一切配置皆协议**\n\nAll provider configurations are loaded from ai-protocol manifests. No provider-specific logic is hardcoded. Adding a new provider requires only a manifest file in ai-protocol.\n\nRouting boundary:\n- spiderswitch exposes runtime/model capability signals only.\n- Routing strategy policy (cost/latency/circuit-breaker/business rules) belongs to upper-layer applications.\n\nDeterministic routing contract:\n- runtime resolution order is fixed as `request runtime_id -\u003e active state runtime_id -\u003e default runtime`.\n- reset supports scoped behavior (`scope=runtime`) to clear a target runtime without global teardown.\n- contract tests in `tests/test_runtime.py` verify resolver order and scoped reset stability.\n\n## Related Projects\n\n- [ai-protocol](https://github.com/hiddenpath/ai-protocol) - Protocol specification\n- [ai-lib-python](https://github.com/hiddenpath/ai-lib-python) - Python runtime SDK\n- [ai-lib-rust](https://github.com/hiddenpath/ai-lib-rust) - Rust runtime SDK\n- [ai-lib-ts](https://github.com/hiddenpath/ai-lib-ts) - TypeScript runtime SDK\n\n## License\n\nThis project is licensed under either of:\n- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n- MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\nat your option.\n\n## Contributing\n\nContributions are welcome! Please ensure:\n1. Code follows PEP 8 and passes `ruff check`\n2. Type hints pass `mypy --strict`\n3. Tests are included for new features\n4. Documentation is updated\n\n---\n\n**spiderswitch** - Where MCP meets ai-lib. 🤖🔀\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhiddenpath%2Fspiderswitch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhiddenpath%2Fspiderswitch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhiddenpath%2Fspiderswitch/lists"}