Skip to main content
Glama
semanticintent

Semantic D1 MCP

Official

validate_database_schema

Validate database schema integrity to detect issues like missing primary keys and orphaned foreign keys in Cloudflare D1 databases.

Instructions

Validate database schema integrity and detect potential issues (missing primary keys, orphaned foreign keys, etc.)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
environmentYesDatabase environment to validate

Implementation Reference

  • Registration of the 'validate_database_schema' MCP tool, including name, description, and input schema definition.
    {
    	name: 'validate_database_schema',
    	description:
    		'Validate database schema integrity and detect potential issues (missing primary keys, orphaned foreign keys, etc.)',
    	inputSchema: {
    		type: 'object',
    		properties: {
    			environment: {
    				type: 'string',
    				enum: ['development', 'staging', 'production'],
    				description: 'Database environment to validate',
    			},
    		},
    		required: ['environment'],
    	},
    },
  • Handler method in MCP server that processes tool calls for 'validate_database_schema' by invoking the ValidateSchemaUseCase.
    private async handleValidateSchema(args: unknown) {
    	const { environment } = args as { environment: string };
    
    	const result = await this.validateSchemaUseCase.execute({
    		environment: parseEnvironment(environment),
    	});
    
    	return {
    		content: [
    			{
    				type: 'text',
    				text: JSON.stringify(result, null, 2),
    			},
    		],
    	};
  • Execute method of ValidateSchemaUseCase that fetches the database schema (with caching), performs validation, and constructs the response.
    async execute(request: ValidateSchemaRequest): Promise<SchemaValidationResponse> {
    	const environment = request.environment;
    
    	// Observable: Cache key based on environment
    	const cacheKey = `schema:${environment}`;
    
    	// Check cache first (avoid repeated API calls)
    	let schema = await this.cache.get<DatabaseSchema>(cacheKey);
    
    	if (!schema) {
    		// Fetch schema from repository
    		const databaseId = this.databaseConfig.getDatabaseId(environment);
    		schema = await this.repository.fetchDatabaseSchema(databaseId);
    
    		// Cache for future requests (10-minute TTL)
    		await this.cache.set(cacheKey, schema, ValidateSchemaUseCase.CACHE_TTL_SECONDS);
    	}
    
    	// Validate schema and collect issues
    	const issues = this.validateSchema(schema);
    
    	// Count issues by severity
    	const errorCount = issues.filter((i) => i.severity === ValidationSeverity.ERROR).length;
    	const warningCount = issues.filter((i) => i.severity === ValidationSeverity.WARNING).length;
    	const infoCount = issues.filter((i) => i.severity === ValidationSeverity.INFO).length;
    
    	return {
    		databaseName: schema.name,
    		environment: schema.environment,
    		isValid: errorCount === 0,
    		errorCount,
    		warningCount,
    		infoCount,
    		issues,
    		validatedAt: new Date(),
    	};
    }
  • Core schema validation logic implementing checks for missing primary keys, orphaned/invalid foreign keys, missing indexes, and nullable FK issues.
    private validateSchema(schema: DatabaseSchema): ValidationIssue[] {
    	const issues: ValidationIssue[] = [];
    
    	// Validate each table
    	for (const table of schema.tables) {
    		// Check for tables without primary key
    		const hasPrimaryKey = table.columns.some((col) => col.isPrimaryKey);
    		if (!hasPrimaryKey) {
    			issues.push({
    				severity: ValidationSeverity.WARNING,
    				category: 'Missing Primary Key',
    				message: `Table '${table.name}' has no primary key`,
    				table: table.name,
    				details: {
    					recommendation: 'Add a primary key column for better query performance and data integrity',
    				},
    			});
    		}
    
    		// Check for orphaned foreign keys (references non-existent tables)
    		for (const fk of table.foreignKeys) {
    			const referencedTableExists = schema.tables.some((t) => t.name === fk.referencesTable);
    			if (!referencedTableExists) {
    				issues.push({
    					severity: ValidationSeverity.ERROR,
    					category: 'Orphaned Foreign Key',
    					message: `Foreign key references non-existent table '${fk.referencesTable}'`,
    					table: table.name,
    					column: fk.column,
    					details: {
    						referencedTable: fk.referencesTable,
    						referencedColumn: fk.referencesColumn,
    					},
    				});
    			} else {
    				// Check if referenced column exists
    				const referencedTable = schema.tables.find((t) => t.name === fk.referencesTable);
    				const referencedColumnExists = referencedTable?.columns.some(
    					(col) => col.name === fk.referencesColumn,
    				);
    				if (!referencedColumnExists) {
    					issues.push({
    						severity: ValidationSeverity.ERROR,
    						category: 'Invalid Foreign Key',
    						message: `Foreign key references non-existent column '${fk.referencesColumn}' in table '${fk.referencesTable}'`,
    						table: table.name,
    						column: fk.column,
    						details: {
    							referencedTable: fk.referencesTable,
    							referencedColumn: fk.referencesColumn,
    						},
    					});
    				}
    			}
    		}
    
    		// Check for tables with no indexes (potential performance issue)
    		if (table.indexes.length === 0 && table.type === 'table') {
    			issues.push({
    				severity: ValidationSeverity.INFO,
    				category: 'No Indexes',
    				message: `Table '${table.name}' has no indexes`,
    				table: table.name,
    				details: {
    					recommendation: 'Consider adding indexes on frequently queried columns',
    				},
    			});
    		}
    
    		// Check for nullable foreign key columns (potential data integrity issue)
    		for (const fk of table.foreignKeys) {
    			const fkColumn = table.columns.find((col) => col.name === fk.column);
    			if (fkColumn?.isNullable && fk.onDelete !== 'SET NULL') {
    				issues.push({
    					severity: ValidationSeverity.WARNING,
    					category: 'Nullable Foreign Key',
    					message: `Nullable foreign key column '${fk.column}' should have ON DELETE SET NULL`,
    					table: table.name,
    					column: fk.column,
    					details: {
    						currentOnDelete: fk.onDelete,
    						recommendation: 'SET NULL',
    					},
    				});
    			}
    		}
    	}
    
    	return issues;
    }
  • Input schema definition for the 'validate_database_schema' tool.
    inputSchema: {
    	type: 'object',
    	properties: {
    		environment: {
    			type: 'string',
    			enum: ['development', 'staging', 'production'],
    			description: 'Database environment to validate',
    		},
    	},
    	required: ['environment'],
    },
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. It mentions what the tool does ('validate' and 'detect') but doesn't describe behavioral traits such as whether it's read-only, if it requires specific permissions, its performance impact, or what the output looks like (e.g., a report or error list). For a validation tool with zero annotation coverage, this is a significant gap.

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 that front-loads the core purpose ('Validate database schema integrity') and adds clarifying examples ('missing primary keys, orphaned foreign keys, etc.') without unnecessary details. Every word earns its place, making it appropriately sized and well-structured.

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

Completeness3/5

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

Given the tool's moderate complexity (validation with potential issues detection), no annotations, and no output schema, the description is minimally adequate. It explains the purpose but lacks details on behavior, output format, or usage context. With no output schema, the agent doesn't know what to expect in return, which is a notable gap for a validation tool.

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?

The input schema has 100% description coverage, with the single parameter 'environment' well-documented in the schema itself (including enum values and description). The description adds no additional meaning about parameters beyond what the schema provides, so the baseline score of 3 is appropriate as 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: 'Validate database schema integrity and detect potential issues' with specific examples like 'missing primary keys, orphaned foreign keys, etc.' It uses a specific verb ('validate') and resource ('database schema'), but doesn't explicitly distinguish it from sibling tools like 'analyze_database_schema' or 'suggest_schema_optimizations' which might have overlapping functionality.

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 its siblings. It doesn't mention alternatives, prerequisites, or exclusions. The agent must infer usage from the tool name and description alone, which is insufficient given the presence of similar tools like 'analyze_database_schema' and 'suggest_schema_optimizations'.

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/semanticintent/semantic-d1-mcp'

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