Skip to main content
Glama
jason-chang

FastAPI OpenAPI MCP Server

by jason-chang

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
NameRequiredDescriptionDefault
pathYes接口路径,例如 /api/v1/users
methodYesHTTP 方法,例如 GET, POST, PUT, DELETE
formatsNo生成的示例格式,默认生成所有格式
include_authNo是否包含认证信息
server_urlNo服务器基础 URL,默认使用 OpenAPI 规范中的服务器 URL
example_strategyNo示例生成策略realistic

Implementation Reference

  • 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
    		)
  • 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'],
    }
  • 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
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. The description only states what the tool does at a high level ('生成各种格式的 API 调用示例'), but doesn't disclose any behavioral traits such as whether it's a read-only operation, if it has side effects, rate limits, authentication requirements, or what the output looks like. For a tool with 6 parameters and no annotations, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence in Chinese that directly states the tool's purpose without any fluff. It's appropriately sized and front-loaded, with every word contributing to understanding the core functionality.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (6 parameters, no output schema, no annotations), the description is incomplete. It doesn't address behavioral aspects, output format, or usage context. While the schema covers parameters well, the description fails to provide the broader context needed for an agent to use this tool effectively, especially for a generation tool that likely produces structured output.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the input schema already documents all parameters thoroughly. The description adds no additional meaning about parameters beyond what's in the schema (e.g., it doesn't explain how 'path' and 'method' interact or what 'example_strategy' entails in practice). Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: '根据 OpenAPI 规范生成各种格式的 API 调用示例' (Generate API call examples in various formats based on OpenAPI specification). It specifies the verb '生成' (generate) and resource 'API 调用示例' (API call examples). However, it doesn't explicitly differentiate from its sibling tool 'search_endpoints', which might have overlapping functionality related to API endpoints.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. There's no mention of the sibling tool 'search_endpoints', nor any context about when this generation tool is appropriate versus searching or other actions. The agent must infer usage solely from the purpose statement.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jason-chang/fastapi-openapi-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server