generate_examples
Generate API call examples in multiple formats (JSON, cURL, Python, etc.) from OpenAPI specifications to demonstrate endpoint usage with configurable authentication and detail levels.
Instructions
根据 OpenAPI 规范生成各种格式的 API 调用示例
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | 接口路径,例如 /api/v1/users | |
| method | Yes | HTTP 方法,例如 GET, POST, PUT, DELETE | |
| formats | No | 生成的示例格式,默认生成所有格式 | |
| include_auth | No | 是否包含认证信息 | |
| server_url | No | 服务器基础 URL,默认使用 OpenAPI 规范中的服务器 URL | |
| example_strategy | No | 示例生成策略 | realistic |
Implementation Reference
- openapi_mcp/tools/examples.py:68-110 (handler)The main handler function (execute method) that orchestrates input validation, endpoint discovery, example generation, and formatted output for the 'generate_examples' tool.async def execute(self, **kwargs: Any) -> CallToolResult: """执行示例生成工具逻辑 Args: **kwargs: 生成参数 Returns: 包含示例的 CallToolResult """ try: # 验证参数 validation_result = self._validate_params(kwargs) if validation_result: return validation_result # 获取 OpenAPI spec spec = self.get_openapi_spec() # 查找接口 endpoint_info = self._find_endpoint(spec, kwargs['path'], kwargs['method']) if not endpoint_info: error_msg = f'❌ 错误: 接口不存在 - {kwargs["method"]} {kwargs["path"]}' return CallToolResult( content=[TextContent(type='text', text=error_msg)], isError=True ) # 准备生成参数 generate_params = self._prepare_generate_params(spec, kwargs) # 生成示例 examples = self._generate_examples(endpoint_info, generate_params) # 格式化输出 output = self._format_examples_output(examples, kwargs.get('formats', [])) return CallToolResult(content=[TextContent(type='text', text=output)]) except Exception as e: error_msg = f'❌ 错误: 示例生成失败 - {type(e).__name__}: {e}' return CallToolResult( content=[TextContent(type='text', text=error_msg)], isError=True )
- openapi_mcp/tools/examples.py:27-66 (schema)Tool name, description, and input schema defining parameters like path, method, formats, etc., for validation.name = 'generate_examples' description = '根据 OpenAPI 规范生成各种格式的 API 调用示例' input_schema = { 'type': 'object', 'properties': { 'path': { 'type': 'string', 'description': '接口路径,例如 /api/v1/users', }, 'method': { 'type': 'string', 'description': 'HTTP 方法,例如 GET, POST, PUT, DELETE', 'enum': ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'], }, 'formats': { 'type': 'array', 'items': { 'type': 'string', 'enum': ['json', 'curl', 'python', 'javascript', 'http', 'postman'], }, 'description': '生成的示例格式,默认生成所有格式', }, 'include_auth': { 'type': 'boolean', 'description': '是否包含认证信息', 'default': True, }, 'server_url': { 'type': 'string', 'description': '服务器基础 URL,默认使用 OpenAPI 规范中的服务器 URL', }, 'example_strategy': { 'type': 'string', 'enum': ['minimal', 'complete', 'realistic'], 'default': 'realistic', 'description': '示例生成策略', }, }, 'required': ['path', 'method'], }
- openapi_mcp/server.py:155-161 (registration)Registration of the GenerateExampleTool instance into the server's tools list during initialization.from openapi_mcp.tools.examples import GenerateExampleTool from openapi_mcp.tools.search import SearchEndpointsTool # 注册 Tools self.tools.append(SearchEndpointsTool(self)) # 增强的搜索工具 self.tools.append(GenerateExampleTool(self)) # 新增的示例生成工具
- Key helper function that generates the core examples dictionary from endpoint information, including parameters, request body, auth, and responses.def _generate_examples( self, endpoint_info: dict[str, Any], params: dict[str, Any] ) -> dict[str, Any]: """生成示例 Args: endpoint_info: 接口信息 params: 生成参数 Returns: 生成的示例字典 """ examples = { 'path': params['path'], 'method': params['method'], 'server_url': params['server_url'], } # 提取接口信息 parameters = endpoint_info.get('parameters', []) request_body = endpoint_info.get('requestBody') responses = endpoint_info.get('responses', {}) # 生成参数示例 examples['parameters'] = self._generate_parameters_example( parameters, params['example_strategy'] ) # 生成请求体示例 if request_body: examples['request_body'] = self._generate_request_body_example( request_body, params['example_strategy'] ) # 生成认证示例 if params['auth_info']: examples['auth'] = self._generate_auth_example(params['auth_info']) # 生成响应示例 examples['responses'] = self._generate_responses_example( responses, params['example_strategy'] ) return examples