Files
n8n-mcp/tests/integration/mcp-protocol/protocol-compliance.test.ts
Romuald Członkowski 9050967cd6 Release v2.24.0: Unified get_node Tool with Code Review Fixes (#437)
* feat(tools): unify node information retrieval with get_node tool

Implements v2.24.0 featuring a unified node information tool that consolidates
get_node_info and get_node_essentials functionality while adding version history
and type structure metadata capabilities.

Key Features:
- Unified get_node tool with progressive detail levels (minimal/standard/full)
- Version history access (versions, compare, breaking changes, migrations)
- Type structure metadata integration from v2.23.0
- Token-efficient defaults optimized for AI agents
- Backward-compatible via private method preservation

Breaking Changes:
- Removed get_node_info tool (replaced by get_node with detail='full')
- Removed get_node_essentials tool (replaced by get_node with detail='standard')
- Tool count: 40 → 39 tools

Implementation:
- src/mcp/tools.ts: Added unified get_node tool definition
- src/mcp/server.ts: Implemented getNode() with 7 mode-specific methods
- Type structure integration via TypeStructureService.getStructure()
- Updated documentation in CHANGELOG.md and README.md
- Version bumped to 2.24.0

Token Costs:
- minimal: ~200 tokens (basic metadata)
- standard: ~1000-2000 tokens (essential properties, default)
- full: ~3000-8000 tokens (complete information)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: update tools-documentation.ts to reference unified get_node tool

Updated all references from deprecated get_node_essentials and get_node_info
to the new unified get_node tool with appropriate detail levels.

Changes:
- Standard Workflow Pattern: Updated to show get_node with detail levels
- Configuration Tools: Replaced two separate tool descriptions with unified get_node
- Performance Characteristics: Updated to reference get_node detail levels
- Usage Notes: Updated recommendation to use get_node with detail='standard'

This completes the v2.24.0 unified get_node tool implementation.
All 13/13 test scenarios passed in n8n-mcp-tester agent validation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Conceived by Romuald Członkowski - www.aiadvisors.pl/en

* test: update tests to reference unified get_node tool

Updated test files to replace references to deprecated get_node_info and
get_node_essentials tools with the new unified get_node tool.

Changes:
- tests/unit/mcp/tools.test.ts: Updated get_node tests and removed references
  to get_node_essentials in toolsWithExamples array and categories object
- tests/unit/mcp/parameter-validation.test.ts: Updated all get_node_info
  references to get_node throughout the test suite

Test results: Successfully reduced test failures from 11 to 3 non-critical failures:
- 1 description length test (expected for unified tool with comprehensive docs)
- 1 database initialization issue (test infrastructure, not related to changes)
- 1 timeout issue (unrelated to changes)

All get_node_info → get_node migration tests now pass successfully.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Conceived by Romuald Członkowski - www.aiadvisors.pl/en

* fix: implement all code review fixes for v2.24.0 unified get_node tool

Comprehensive improvements addressing all critical, high-priority, and code quality issues identified in code review.

## Critical Fixes (Phase 1)
- Add missing getNode mock in parameter-validation tests
- Shorten tool description from 670 to 288 characters (under 300 limit)

## High Priority Fixes (Phase 2)
- Add null safety check in enrichPropertyWithTypeInfo (prevent crashes on null properties)
- Add nodeType context to all error messages in handleVersionMode (better debugging)
- Optimize version summary fetch (conditional on detail level, skip for minimal mode)
- Add comprehensive parameter validation for detail and mode with clear error messages

## Code Quality Improvements (Phase 3)
- Refactor property enrichment with new enrichPropertiesWithTypeInfo helper (eliminate duplication)
- Add TypeScript interfaces for all return types (replace any with proper union types)
- Implement version data caching with 24-hour TTL (improve performance)
- Enhance JSDoc documentation with detailed parameter explanations

## New TypeScript Interfaces
- VersionSummary: Version metadata structure
- NodeMinimalInfo: ~200 token response for minimal detail
- NodeStandardInfo: ~1-2K token response for standard detail
- NodeFullInfo: ~3-8K token response for full detail
- VersionHistoryInfo: Version history response
- VersionComparisonInfo: Version comparison response
- NodeInfoResponse: Union type for all possible responses

## Testing
- All 130 test files passed (3778 tests, 42 skipped)
- Build successful with no TypeScript errors
- Proper test mocking for unified get_node tool

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: update integration tests to use unified get_node tool

Replace all references to deprecated get_node_info and get_node_essentials
with the new unified get_node tool in integration tests.

## Changes
- Replace get_node_info → get_node in 6 integration test files
- Replace get_node_essentials → get_node in 2 integration test files
- All tool calls now use unified interface

## Files Updated
- tests/integration/mcp-protocol/error-handling.test.ts
- tests/integration/mcp-protocol/performance.test.ts
- tests/integration/mcp-protocol/session-management.test.ts
- tests/integration/mcp-protocol/tool-invocation.test.ts
- tests/integration/mcp-protocol/protocol-compliance.test.ts
- tests/integration/telemetry/mcp-telemetry.test.ts

This fixes CI test failures caused by calling removed tools.

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* test: add comprehensive tests for unified get_node tool

Add 81 comprehensive unit tests for the unified get_node tool to improve
code coverage of the v2.24.0 implementation.

## Test Coverage

### Parameter Validation (6 tests)
- Invalid detail/mode validation with clear error messages
- All valid parameter combinations
- Default values and node type normalization

### Info Mode Tests (21 tests)
- Minimal detail: Basic metadata only, no version info (~200 tokens)
- Standard detail: Essentials with version info (~1-2K tokens)
- Full detail: Complete info with version info (~3-8K tokens)
- includeTypeInfo and includeExamples parameter handling

### Version Mode Tests (24 tests)
- versions: Version history and details
- compare: Version comparison with proper error handling
- breaking: Breaking changes with upgradeSafe flags
- migrations: Auto-migratable changes detection

### Helper Methods (18 tests)
- enrichPropertyWithTypeInfo: Null safety, type handling, structure hints
- enrichPropertiesWithTypeInfo: Array handling, mixed properties
- getVersionSummary: Caching with 24-hour TTL

### Error Handling (3 tests)
- Repository initialization checks
- NodeType context in error messages
- Invalid mode/detail handling

### Integration Tests (8 tests)
- Mode routing logic
- Cache effectiveness across calls
- Type safety validation
- Edge cases (empty data, alternatives, long names)

## Results
- 81 tests passing
- 100% coverage of new get_node methods
- All parameter combinations tested
- All error conditions covered

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: update integration test assertions for unified get_node tool

Updated integration tests to match the new unified get_node response structure:
- error-handling.test.ts: Added detail='full' parameter for large payload test
- tool-invocation.test.ts: Updated property assertions for standard/full detail levels
- Fixed duplicate describe block and comparison logic

Conceived by Romuald Członkowski - www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: correct property names in integration test for standard detail

Updated test to check for requiredProperties and commonProperties
instead of essentialProperties to match actual get_node response structure.

Conceived by Romuald Członkowski - www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-24 17:06:21 +01:00

297 lines
10 KiB
TypeScript

import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { TestableN8NMCPServer } from './test-helpers';
describe('MCP Protocol Compliance', () => {
let mcpServer: TestableN8NMCPServer;
let transport: InMemoryTransport;
let client: Client;
beforeEach(async () => {
mcpServer = new TestableN8NMCPServer();
await mcpServer.initialize();
const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();
transport = serverTransport;
// Connect MCP server to transport
await mcpServer.connectToTransport(transport);
// Create client
client = new Client({
name: 'test-client',
version: '1.0.0'
}, {
capabilities: {}
});
await client.connect(clientTransport);
});
afterEach(async () => {
await client.close();
await mcpServer.close();
});
describe('JSON-RPC 2.0 Compliance', () => {
it('should return proper JSON-RPC 2.0 response format', async () => {
const response = await client.listTools();
// Response should have tools array
expect(response).toHaveProperty('tools');
expect(Array.isArray((response as any).tools)).toBe(true);
});
it('should handle request with id correctly', async () => {
const response = await client.listTools();
expect(response).toBeDefined();
expect(typeof response).toBe('object');
});
it('should handle batch requests', async () => {
// Send multiple requests concurrently
const promises = [
client.listTools(),
client.listTools(),
client.listTools()
];
const responses = await Promise.all(promises);
expect(responses).toHaveLength(3);
responses.forEach(response => {
expect(response).toHaveProperty('tools');
});
});
it('should preserve request order in responses', async () => {
const requests = [];
const expectedOrder = [];
// Create requests with different tools to track order
for (let i = 0; i < 5; i++) {
expectedOrder.push(i);
requests.push(
client.callTool({ name: 'get_database_statistics', arguments: {} })
.then(() => i)
);
}
const results = await Promise.all(requests);
expect(results).toEqual(expectedOrder);
});
});
describe('Protocol Version Negotiation', () => {
it('should negotiate protocol capabilities', async () => {
const serverInfo = await client.getServerVersion();
expect(serverInfo).toHaveProperty('name');
expect(serverInfo).toHaveProperty('version');
expect(serverInfo!.name).toBe('n8n-documentation-mcp');
});
it('should expose supported capabilities', async () => {
const serverCapabilities = client.getServerCapabilities();
expect(serverCapabilities).toBeDefined();
// Should support tools
expect(serverCapabilities).toHaveProperty('tools');
});
});
describe('Message Format Validation', () => {
it('should reject messages without method', async () => {
// Test by sending raw message through transport
const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();
const testClient = new Client({ name: 'test', version: '1.0.0' }, {});
await mcpServer.connectToTransport(serverTransport);
await testClient.connect(clientTransport);
try {
// This should fail as MCP SDK validates method
await (testClient as any).request({ method: '', params: {} });
expect.fail('Should have thrown an error');
} catch (error) {
expect(error).toBeDefined();
} finally {
await testClient.close();
}
});
it('should handle missing params gracefully', async () => {
// Most tools should work without params
const response = await client.callTool({ name: 'list_nodes', arguments: {} });
expect(response).toBeDefined();
});
it('should validate params schema', async () => {
try {
// Invalid nodeType format (missing prefix)
const response = await client.callTool({ name: 'get_node', arguments: {
nodeType: 'httpRequest' // Should be 'nodes-base.httpRequest'
} });
// Check if the response indicates an error
const text = (response as any).content[0].text;
expect(text).toContain('not found');
} catch (error: any) {
// If it throws, that's also acceptable
expect(error.message).toContain('not found');
}
});
});
describe('Content Types', () => {
it('should handle text content in tool responses', async () => {
const response = await client.callTool({ name: 'get_database_statistics', arguments: {} });
expect((response as any).content).toHaveLength(1);
expect((response as any).content[0]).toHaveProperty('type', 'text');
expect((response as any).content[0]).toHaveProperty('text');
expect(typeof (response as any).content[0].text).toBe('string');
});
it('should handle large text responses', async () => {
// Get a large node info response
const response = await client.callTool({ name: 'get_node', arguments: {
nodeType: 'nodes-base.httpRequest'
} });
expect((response as any).content).toHaveLength(1);
expect((response as any).content[0].type).toBe('text');
expect((response as any).content[0].text.length).toBeGreaterThan(1000);
});
it('should handle JSON content properly', async () => {
const response = await client.callTool({ name: 'list_nodes', arguments: {
limit: 5
} });
expect((response as any).content).toHaveLength(1);
const content = JSON.parse((response as any).content[0].text);
expect(content).toHaveProperty('nodes');
expect(Array.isArray(content.nodes)).toBe(true);
});
});
describe('Request/Response Correlation', () => {
it('should correlate concurrent requests correctly', async () => {
const requests = [
client.callTool({ name: 'get_node', arguments: { nodeType: 'nodes-base.httpRequest' } }),
client.callTool({ name: 'get_node', arguments: { nodeType: 'nodes-base.webhook' } }),
client.callTool({ name: 'get_node', arguments: { nodeType: 'nodes-base.slack' } })
];
const responses = await Promise.all(requests);
expect((responses[0] as any).content[0].text).toContain('httpRequest');
expect((responses[1] as any).content[0].text).toContain('webhook');
expect((responses[2] as any).content[0].text).toContain('slack');
});
it('should handle interleaved requests', async () => {
const results: string[] = [];
// Start multiple requests with different delays
const p1 = client.callTool({ name: 'get_database_statistics', arguments: {} })
.then(() => { results.push('stats'); return 'stats'; });
const p2 = client.callTool({ name: 'list_nodes', arguments: { limit: 1 } })
.then(() => { results.push('nodes'); return 'nodes'; });
const p3 = client.callTool({ name: 'search_nodes', arguments: { query: 'http' } })
.then(() => { results.push('search'); return 'search'; });
const resolved = await Promise.all([p1, p2, p3]);
// All should complete
expect(resolved).toHaveLength(3);
expect(results).toHaveLength(3);
});
});
describe('Protocol Extensions', () => {
it('should handle tool-specific extensions', async () => {
// Test tool with complex params
const response = await client.callTool({ name: 'validate_node_operation', arguments: {
nodeType: 'nodes-base.httpRequest',
config: {
method: 'GET',
url: 'https://api.example.com'
},
profile: 'runtime'
} });
expect((response as any).content).toHaveLength(1);
expect((response as any).content[0].type).toBe('text');
});
it('should support optional parameters', async () => {
// Call with minimal params
const response1 = await client.callTool({ name: 'list_nodes', arguments: {} });
// Call with all params
const response2 = await client.callTool({ name: 'list_nodes', arguments: {
limit: 10,
category: 'trigger',
package: 'n8n-nodes-base'
} });
expect(response1).toBeDefined();
expect(response2).toBeDefined();
});
});
describe('Transport Layer', () => {
it('should handle transport disconnection gracefully', async () => {
const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();
const testClient = new Client({ name: 'test', version: '1.0.0' }, {});
await mcpServer.connectToTransport(serverTransport);
await testClient.connect(clientTransport);
// Make a request
const response = await testClient.callTool({ name: 'get_database_statistics', arguments: {} });
expect(response).toBeDefined();
// Close client
await testClient.close();
// Further requests should fail
try {
await testClient.callTool({ name: 'get_database_statistics', arguments: {} });
expect.fail('Should have thrown an error');
} catch (error) {
expect(error).toBeDefined();
}
});
it('should handle multiple sequential connections', async () => {
// Close existing connection
await client.close();
await mcpServer.close();
// Create new connections
for (let i = 0; i < 3; i++) {
const engine = new TestableN8NMCPServer();
await engine.initialize();
const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();
await engine.connectToTransport(serverTransport);
const testClient = new Client({ name: 'test', version: '1.0.0' }, {});
await testClient.connect(clientTransport);
const response = await testClient.callTool({ name: 'get_database_statistics', arguments: {} });
expect(response).toBeDefined();
await testClient.close();
await engine.close();
}
});
});
});