MCP (Model Context Protocol) Integration Guide v0.1.18.0¶
Overview¶
NetIntel-OCR v0.1.18.0 provides comprehensive MCP (Model Context Protocol) support, enabling seamless integration with AI assistants and LLM agents. This guide covers all 15 tools, 6 resources, and 5 prompts available in the MCP implementation.
Table of Contents¶
MCP Server Setup¶
Starting the MCP Server¶
# Start MCP server
netintel-ocr server mcp --port 3000
# Start with specific configuration
netintel-ocr server mcp --port 3000 --config mcp-config.yml
# Start all servers (API + MCP)
netintel-ocr server all --api-port 8000 --mcp-port 3000
Configuration¶
# mcp-config.yml
mcp:
server:
port: 3000
host: 0.0.0.0
cors_enabled: true
allowed_origins:
- http://localhost:*
- https://claude.ai
rate_limiting:
enabled: true
requests_per_minute: 100
burst_size: 20
authentication:
enabled: true
api_key_header: X-MCP-API-Key
tools:
enabled: true
timeout: 30000 # 30 seconds
resources:
enabled: true
cache_ttl: 3600 # 1 hour
prompts:
enabled: true
max_context_size: 100000
Connecting from Claude or Other LLMs¶
// claude_config.json
{
"mcpServers": {
"netintel-ocr": {
"command": "netintel-ocr",
"args": ["server", "mcp"],
"env": {
"NETINTEL_API_KEY": "your-api-key"
}
}
}
}
MCP Tools¶
NetIntel-OCR provides 15 specialized tools for document intelligence operations.
Document Operations Tools (5)¶
1. intelligent_query¶
Performs intelligent queries with automatic mode selection.
// Tool Definition
{
name: "intelligent_query",
description: "Smart query with auto mode selection based on query intent",
parameters: {
query: string,
mode?: "auto" | "vector" | "kg" | "hybrid",
filters?: {
document_type?: string[],
date_range?: { start: string, end: string },
confidence_min?: number
},
max_results?: number
}
}
// Example Usage
const result = await mcp.callTool("intelligent_query", {
query: "Find all firewall configurations in the network diagrams",
mode: "auto",
filters: {
document_type: ["network_diagram"],
confidence_min: 0.8
},
max_results: 10
});
2. compare_documents¶
Compares multiple documents to find similarities and differences.
// Tool Definition
{
name: "compare_documents",
description: "Compare multiple documents for similarities and differences",
parameters: {
document_ids: string[],
comparison_type: "content" | "structure" | "entities" | "all",
include_visualizations?: boolean
}
}
// Example Usage
const comparison = await mcp.callTool("compare_documents", {
document_ids: ["doc_123", "doc_456", "doc_789"],
comparison_type: "all",
include_visualizations: true
});
3. analyze_network_path¶
Analyzes network paths and connections in diagrams.
// Tool Definition
{
name: "analyze_network_path",
description: "Analyze network paths and connections",
parameters: {
start_point: string,
end_point?: string,
path_type: "shortest" | "all" | "secure" | "redundant",
include_metrics?: boolean
}
}
// Example Usage
const analysis = await mcp.callTool("analyze_network_path", {
start_point: "internet_gateway",
end_point: "database_server",
path_type: "secure",
include_metrics: true
});
4. check_compliance¶
Checks documents against compliance standards.
// Tool Definition
{
name: "check_compliance",
description: "Check documents against compliance standards",
parameters: {
document_id: string,
standards: string[], // ["PCI-DSS", "HIPAA", "SOC2", etc.]
detailed_report?: boolean
}
}
// Example Usage
const compliance = await mcp.callTool("check_compliance", {
document_id: "doc_123",
standards: ["PCI-DSS", "SOC2"],
detailed_report: true
});
5. extract_entities¶
Extracts named entities from documents.
// Tool Definition
{
name: "extract_entities",
description: "Extract named entities from documents",
parameters: {
document_id: string,
entity_types?: string[], // ["IP", "HOSTNAME", "PERSON", etc.]
confidence_threshold?: number,
include_relationships?: boolean
}
}
// Example Usage
const entities = await mcp.callTool("extract_entities", {
document_id: "doc_123",
entity_types: ["IP_ADDRESS", "HOSTNAME", "NETWORK_DEVICE"],
confidence_threshold: 0.7,
include_relationships: true
});
Milvus Operations Tools (5)¶
6. create_milvus_collection¶
Creates a new Milvus collection with schema.
// Tool Definition
{
name: "create_milvus_collection",
description: "Create a new Milvus collection with schema",
parameters: {
collection_name: string,
dimension: number,
index_type?: string,
metric_type?: string,
additional_fields?: Array<{
name: string,
type: string,
max_length?: number
}>
}
}
// Example Usage
const collection = await mcp.callTool("create_milvus_collection", {
collection_name: "network_diagrams",
dimension: 768,
index_type: "IVF_FLAT",
metric_type: "L2",
additional_fields: [
{ name: "content", type: "varchar", max_length: 65535 },
{ name: "metadata", type: "json" }
]
});
7. milvus_vector_search¶
Performs vector similarity search in Milvus.
// Tool Definition
{
name: "milvus_vector_search",
description: "Perform vector similarity search",
parameters: {
collection_name: string,
query_vector: number[] | string, // vector or text to embed
top_k?: number,
filter?: string,
output_fields?: string[]
}
}
// Example Usage
const results = await mcp.callTool("milvus_vector_search", {
collection_name: "documents",
query_vector: "firewall configuration best practices",
top_k: 5,
filter: "category == 'security'",
output_fields: ["content", "metadata", "score"]
});
8. milvus_hybrid_search¶
Performs hybrid search combining vector and scalar filters.
// Tool Definition
{
name: "milvus_hybrid_search",
description: "Hybrid search combining vector and scalar conditions",
parameters: {
collection_name: string,
vector_query: number[] | string,
scalar_filters: object,
alpha?: number, // weight between vector and scalar (0-1)
top_k?: number
}
}
// Example Usage
const results = await mcp.callTool("milvus_hybrid_search", {
collection_name: "documents",
vector_query: "network security",
scalar_filters: {
date: { "$gte": "2024-01-01" },
type: { "$in": ["diagram", "architecture"] }
},
alpha: 0.7,
top_k: 10
});
9. manage_milvus_collection¶
Manages Milvus collection operations.
// Tool Definition
{
name: "manage_milvus_collection",
description: "Manage Milvus collection operations",
parameters: {
collection_name: string,
operation: "load" | "release" | "flush" | "compact" | "drop",
params?: object
}
}
// Example Usage
await mcp.callTool("manage_milvus_collection", {
collection_name: "documents",
operation: "load",
params: { replica_number: 2 }
});
10. get_collection_stats¶
Retrieves collection statistics and metrics.
// Tool Definition
{
name: "get_collection_stats",
description: "Get collection statistics and metrics",
parameters: {
collection_name: string,
include_index_info?: boolean,
include_segments?: boolean
}
}
// Example Usage
const stats = await mcp.callTool("get_collection_stats", {
collection_name: "documents",
include_index_info: true,
include_segments: true
});
Knowledge Graph Operations Tools (5)¶
11. kg_initialize¶
Initializes FalkorDB knowledge graph.
// Tool Definition
{
name: "kg_initialize",
description: "Initialize FalkorDB knowledge graph",
parameters: {
graph_name?: string,
clear_existing?: boolean,
schema?: object
}
}
// Example Usage
await mcp.callTool("kg_initialize", {
graph_name: "network_topology",
clear_existing: false,
schema: {
nodes: ["Device", "Network", "Application"],
relationships: ["CONNECTS_TO", "HOSTS", "DEPENDS_ON"]
}
});
12. kg_cypher_query¶
Executes Cypher queries on the knowledge graph.
// Tool Definition
{
name: "kg_cypher_query",
description: "Execute Cypher queries on knowledge graph",
parameters: {
query: string,
params?: object,
explain?: boolean
}
}
// Example Usage
const result = await mcp.callTool("kg_cypher_query", {
query: `
MATCH (fw:Firewall)-[:PROTECTS]->(n:Network)
WHERE n.zone = $zone
RETURN fw.name, fw.rules, n.name
`,
params: { zone: "DMZ" }
});
13. kg_hybrid_search¶
Performs hybrid search using KG and vector embeddings.
// Tool Definition
{
name: "kg_hybrid_search",
description: "Hybrid search combining KG and vectors",
parameters: {
query: string,
strategy: "adaptive" | "vector_first" | "graph_first" | "parallel",
max_hops?: number,
include_embeddings?: boolean
}
}
// Example Usage
const results = await mcp.callTool("kg_hybrid_search", {
query: "Find all paths from DMZ to internal network",
strategy: "adaptive",
max_hops: 3,
include_embeddings: true
});
14. kg_find_paths¶
Finds paths between entities in the knowledge graph.
// Tool Definition
{
name: "kg_find_paths",
description: "Find paths between entities",
parameters: {
start_entity: string,
end_entity: string,
max_length?: number,
path_type?: "shortest" | "all" | "no_loops",
relationship_types?: string[]
}
}
// Example Usage
const paths = await mcp.callTool("kg_find_paths", {
start_entity: "web_server",
end_entity: "database",
max_length: 5,
path_type: "shortest",
relationship_types: ["CONNECTS_TO", "ROUTES_THROUGH"]
});
15. kg_rag_query¶
Performs RAG-powered queries using knowledge graph context.
// Tool Definition
{
name: "kg_rag_query",
description: "RAG-powered query using KG context",
parameters: {
question: string,
mode: "kg_only" | "vector_only" | "hybrid",
context_size?: number,
include_reasoning?: boolean
}
}
// Example Usage
const answer = await mcp.callTool("kg_rag_query", {
question: "What are the security vulnerabilities in our DMZ architecture?",
mode: "hybrid",
context_size: 5000,
include_reasoning: true
});
MCP Resources¶
NetIntel-OCR provides 6 interactive resources for exploration and visualization.
1. document://explore/{id}¶
Interactive document exploration interface.
// Resource Definition
{
uri: "document://explore/{document_id}",
name: "Document Explorer",
description: "Interactive document exploration with search and navigation",
mimeType: "text/html"
}
// Example Usage
const explorer = await mcp.readResource("document://explore/doc_123");
// Returns interactive HTML interface with:
// - Document content viewer
// - Search within document
// - Entity highlighting
// - Navigation sidebar
// - Export options
2. topology://visualize/{id}¶
Network topology visualization.
// Resource Definition
{
uri: "topology://visualize/{topology_id}",
name: "Topology Visualizer",
description: "Interactive network topology visualization",
mimeType: "text/html"
}
// Example Usage
const visualizer = await mcp.readResource("topology://visualize/network_001");
// Returns interactive visualization with:
// - Zoomable network diagram
// - Node details on click
// - Path highlighting
// - Traffic flow animation
// - Export to various formats
3. kg://explore/{id}¶
Knowledge graph exploration interface.
// Resource Definition
{
uri: "kg://explore/{graph_id}",
name: "KG Explorer",
description: "Interactive knowledge graph exploration",
mimeType: "text/html"
}
// Example Usage
const kgExplorer = await mcp.readResource("kg://explore/main_graph");
// Returns interactive KG interface with:
// - Graph visualization
// - Query builder
// - Node/edge filtering
// - Pattern matching
// - Export capabilities
4. milvus://collection/{name}¶
Milvus collection exploration.
// Resource Definition
{
uri: "milvus://collection/{collection_name}",
name: "Collection Explorer",
description: "Explore Milvus collection data and schema",
mimeType: "application/json"
}
// Example Usage
const collection = await mcp.readResource("milvus://collection/documents");
// Returns collection details:
{
"name": "documents",
"schema": { /* field definitions */ },
"statistics": {
"row_count": 10000,
"index_info": { /* index details */ }
},
"sample_data": [ /* sample vectors */ ]
}
5. milvus://search/{name}¶
Milvus search interface.
// Resource Definition
{
uri: "milvus://search/{collection_name}",
name: "Search Interface",
description: "Interactive search interface for Milvus collection",
mimeType: "text/html"
}
// Example Usage
const searchUI = await mcp.readResource("milvus://search/documents");
// Returns search interface with:
// - Query input
// - Filter builder
// - Result visualization
// - Export options
// - Search history
6. config://system¶
System configuration viewer.
// Resource Definition
{
uri: "config://system",
name: "System Configuration",
description: "View and validate system configuration",
mimeType: "application/json"
}
// Example Usage
const config = await mcp.readResource("config://system");
// Returns system configuration:
{
"version": "0.1.18.0",
"modules": {
"kg": { "enabled": true, "version": "1.0.0" },
"vector": { "enabled": true, "backend": "milvus" },
"api": { "enabled": true, "port": 8000 }
},
"services": {
"milvus": { "status": "connected", "collections": 5 },
"falkordb": { "status": "connected", "graphs": 2 },
"ollama": { "status": "connected", "models": 3 }
}
}
MCP Prompts¶
NetIntel-OCR provides 5 specialized prompts for contextual operations.
1. contextual_analysis¶
Performs contextual analysis with memory of previous interactions.
// Prompt Definition
{
name: "contextual_analysis",
description: "Analyze with context from previous interactions",
arguments: [
{ name: "query", type: "string", required: true },
{ name: "context_window", type: "number", default: 5 },
{ name: "include_history", type: "boolean", default: true }
]
}
// Example Usage
const analysis = await mcp.callPrompt("contextual_analysis", {
query: "How has our network security posture changed?",
context_window: 10,
include_history: true
});
// Returns contextual analysis considering:
// - Previous queries and results
// - Document history
// - Temporal patterns
// - Trend analysis
2. synthesize_documents¶
Synthesizes information from multiple documents.
// Prompt Definition
{
name: "synthesize_documents",
description: "Synthesize insights from multiple documents",
arguments: [
{ name: "document_ids", type: "array", required: true },
{ name: "synthesis_type", type: "string", default: "comprehensive" },
{ name: "focus_areas", type: "array", optional: true }
]
}
// Example Usage
const synthesis = await mcp.callPrompt("synthesize_documents", {
document_ids: ["doc_123", "doc_456", "doc_789"],
synthesis_type: "security_focused",
focus_areas: ["vulnerabilities", "recommendations"]
});
// Returns synthesized report with:
// - Key findings across documents
// - Common patterns
// - Contradictions or gaps
// - Unified recommendations
3. troubleshooting_guide¶
Generates troubleshooting guides based on issues.
// Prompt Definition
{
name: "troubleshooting_guide",
description: "Generate troubleshooting guide for issues",
arguments: [
{ name: "issue_description", type: "string", required: true },
{ name: "system_context", type: "object", optional: true },
{ name: "detail_level", type: "string", default: "standard" }
]
}
// Example Usage
const guide = await mcp.callPrompt("troubleshooting_guide", {
issue_description: "Network connectivity issues in DMZ",
system_context: {
topology: "topology_001",
recent_changes: ["firewall_update", "vlan_reconfiguration"]
},
detail_level: "detailed"
});
// Returns troubleshooting guide with:
// - Step-by-step diagnosis procedures
// - Common causes and solutions
// - Verification steps
// - Escalation paths
4. security_audit_prompt¶
Performs security audit analysis.
// Prompt Definition
{
name: "security_audit_prompt",
description: "Perform security audit analysis",
arguments: [
{ name: "scope", type: "object", required: true },
{ name: "standards", type: "array", default: ["CIS", "NIST"] },
{ name: "risk_assessment", type: "boolean", default: true }
]
}
// Example Usage
const audit = await mcp.callPrompt("security_audit_prompt", {
scope: {
documents: ["network_diagram_001", "security_policy_002"],
systems: ["firewall", "ids", "vpn"]
},
standards: ["CIS", "PCI-DSS", "ISO27001"],
risk_assessment: true
});
// Returns audit report with:
// - Compliance status per standard
// - Identified vulnerabilities
// - Risk scores and rankings
// - Remediation recommendations
// - Priority action items
5. network_design_review¶
Reviews network design for best practices.
// Prompt Definition
{
name: "network_design_review",
description: "Review network design against best practices",
arguments: [
{ name: "design_document", type: "string", required: true },
{ name: "review_aspects", type: "array", optional: true },
{ name: "include_alternatives", type: "boolean", default: false }
]
}
// Example Usage
const review = await mcp.callPrompt("network_design_review", {
design_document: "doc_network_arch_v2",
review_aspects: ["scalability", "security", "redundancy", "performance"],
include_alternatives: true
});
// Returns design review with:
// - Strengths and weaknesses
// - Best practice violations
// - Scalability analysis
// - Security assessment
// - Alternative design suggestions
// - Implementation roadmap
Integration Examples¶
Example 1: Complete Document Analysis Pipeline¶
// Complete document analysis using MCP tools
async function analyzeDocument(documentPath) {
// 1. Upload and process document
const doc = await uploadDocument(documentPath);
// 2. Extract entities
const entities = await mcp.callTool("extract_entities", {
document_id: doc.id,
entity_types: ["NETWORK_DEVICE", "IP_ADDRESS", "PROTOCOL"],
include_relationships: true
});
// 3. Initialize knowledge graph
await mcp.callTool("kg_initialize", {
graph_name: `doc_${doc.id}_graph`
});
// 4. Build knowledge graph from entities
for (const entity of entities.entities) {
await mcp.callTool("kg_cypher_query", {
query: `
MERGE (e:Entity {name: $name, type: $type})
SET e.properties = $properties
`,
params: {
name: entity.value,
type: entity.type,
properties: entity.metadata
}
});
}
// 5. Create relationships
for (const rel of entities.relationships) {
await mcp.callTool("kg_cypher_query", {
query: `
MATCH (a:Entity {name: $from})
MATCH (b:Entity {name: $to})
MERGE (a)-[r:${rel.type}]->(b)
SET r.properties = $properties
`,
params: {
from: rel.from,
to: rel.to,
properties: rel.metadata
}
});
}
// 6. Perform security audit
const audit = await mcp.callPrompt("security_audit_prompt", {
scope: { documents: [doc.id] },
standards: ["CIS", "NIST"],
risk_assessment: true
});
// 7. Generate vector embeddings
await mcp.callTool("create_milvus_collection", {
collection_name: `doc_${doc.id}_vectors`,
dimension: 768
});
// 8. Index document chunks
for (const chunk of doc.chunks) {
await mcp.callTool("milvus_vector_search", {
collection_name: `doc_${doc.id}_vectors`,
query_vector: chunk.embedding,
top_k: 1
});
}
return {
document: doc,
entities: entities,
audit: audit,
graph: `kg://explore/doc_${doc.id}_graph`,
search: `milvus://search/doc_${doc.id}_vectors`
};
}
Example 2: Network Topology Analysis¶
// Analyze network topology using MCP
async function analyzeNetworkTopology(topologyId) {
// 1. Load topology
const topology = await mcp.readResource(`topology://visualize/${topologyId}`);
// 2. Find critical paths
const criticalPaths = await mcp.callTool("analyze_network_path", {
start_point: "internet",
end_point: "database_tier",
path_type: "all",
include_metrics: true
});
// 3. Identify single points of failure
const spof = await mcp.callTool("kg_cypher_query", {
query: `
MATCH (n:NetworkDevice)
WHERE NOT EXISTS((n)-[:HAS_BACKUP]->())
AND size((n)<-[:DEPENDS_ON]-()) > 3
RETURN n.name as device,
size((n)<-[:DEPENDS_ON]-()) as dependencies
ORDER BY dependencies DESC
`
});
// 4. Check compliance
const compliance = await mcp.callTool("check_compliance", {
document_id: topologyId,
standards: ["PCI-DSS", "HIPAA"],
detailed_report: true
});
// 5. Generate design review
const review = await mcp.callPrompt("network_design_review", {
design_document: topologyId,
review_aspects: ["security", "redundancy", "scalability"],
include_alternatives: true
});
return {
topology: topology,
critical_paths: criticalPaths,
single_points_of_failure: spof,
compliance: compliance,
review: review
};
}
Example 3: Intelligent Search with Context¶
// Perform intelligent contextual search
async function intelligentSearch(query, context = {}) {
// 1. Classify query intent
const classification = await mcp.callTool("intelligent_query", {
query: query,
mode: "auto"
});
// 2. Perform appropriate search based on classification
let results;
switch (classification.suggested_mode) {
case "kg":
// Knowledge graph search
results = await mcp.callTool("kg_hybrid_search", {
query: query,
strategy: "graph_first",
max_hops: 3
});
break;
case "vector":
// Vector similarity search
results = await mcp.callTool("milvus_vector_search", {
collection_name: "documents",
query_vector: query,
top_k: 10
});
break;
case "hybrid":
// Hybrid search
results = await mcp.callTool("milvus_hybrid_search", {
collection_name: "documents",
vector_query: query,
scalar_filters: context.filters || {},
alpha: 0.7
});
break;
default:
// RAG-based search
results = await mcp.callTool("kg_rag_query", {
question: query,
mode: "hybrid",
context_size: 5000
});
}
// 3. Apply contextual analysis
const contextualResults = await mcp.callPrompt("contextual_analysis", {
query: query,
context_window: 5,
include_history: true
});
// 4. Synthesize final results
const synthesis = await mcp.callPrompt("synthesize_documents", {
document_ids: results.documents.map(d => d.id),
synthesis_type: "query_focused",
focus_areas: [query]
});
return {
mode: classification.suggested_mode,
results: results,
context: contextualResults,
synthesis: synthesis
};
}
Best Practices¶
1. Tool Selection¶
Choose the right tool for your use case:
// Decision tree for tool selection
function selectTool(intent) {
const toolMap = {
// Document operations
"compare": "compare_documents",
"extract": "extract_entities",
"compliance": "check_compliance",
// Search operations
"semantic_search": "milvus_vector_search",
"filtered_search": "milvus_hybrid_search",
"relationship_search": "kg_cypher_query",
// Analysis operations
"network_analysis": "analyze_network_path",
"path_finding": "kg_find_paths",
"question_answering": "kg_rag_query"
};
return toolMap[intent] || "intelligent_query";
}
2. Error Handling¶
Implement robust error handling:
async function safeMCPCall(tool, params, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const result = await mcp.callTool(tool, params);
// Check for partial failures
if (result.warnings) {
console.warn(`Tool ${tool} completed with warnings:`, result.warnings);
}
return result;
} catch (error) {
console.error(`Attempt ${i + 1} failed for ${tool}:`, error);
if (i === retries - 1) {
// Final attempt failed
throw new Error(`Tool ${tool} failed after ${retries} attempts: ${error.message}`);
}
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
}
3. Resource Caching¶
Cache resource responses for better performance:
class MCPResourceCache {
constructor(ttl = 3600000) { // 1 hour default
this.cache = new Map();
this.ttl = ttl;
}
async getResource(uri) {
const cached = this.cache.get(uri);
if (cached && Date.now() - cached.timestamp < this.ttl) {
return cached.data;
}
const data = await mcp.readResource(uri);
this.cache.set(uri, {
data: data,
timestamp: Date.now()
});
return data;
}
invalidate(uri) {
this.cache.delete(uri);
}
}
4. Batch Operations¶
Batch operations for efficiency:
async function batchMCPOperations(operations) {
// Group operations by type
const grouped = operations.reduce((acc, op) => {
if (!acc[op.tool]) acc[op.tool] = [];
acc[op.tool].push(op.params);
return acc;
}, {});
// Execute batches in parallel
const results = await Promise.all(
Object.entries(grouped).map(async ([tool, paramsList]) => {
// Some tools support batch operations directly
if (tool === "milvus_vector_search") {
return await mcp.callTool(tool, {
batch: paramsList
});
}
// Others need parallel execution
return await Promise.all(
paramsList.map(params => mcp.callTool(tool, params))
);
})
);
return results.flat();
}
5. Context Management¶
Manage context effectively for prompts:
class ContextManager {
constructor(maxSize = 100000) {
this.context = [];
this.maxSize = maxSize;
}
addContext(item) {
this.context.push({
...item,
timestamp: Date.now()
});
// Trim if exceeds max size
this.trimContext();
}
trimContext() {
let totalSize = JSON.stringify(this.context).length;
while (totalSize > this.maxSize && this.context.length > 0) {
this.context.shift(); // Remove oldest
totalSize = JSON.stringify(this.context).length;
}
}
getRelevantContext(query, limit = 5) {
// Sort by relevance and recency
return this.context
.sort((a, b) => {
const relevanceA = this.calculateRelevance(query, a);
const relevanceB = this.calculateRelevance(query, b);
return (relevanceB + b.timestamp) - (relevanceA + a.timestamp);
})
.slice(0, limit);
}
calculateRelevance(query, item) {
// Simple keyword matching (can be enhanced)
const keywords = query.toLowerCase().split(' ');
const itemText = JSON.stringify(item).toLowerCase();
return keywords.filter(k => itemText.includes(k)).length;
}
}
Troubleshooting¶
Common Issues¶
1. MCP Server Connection Failed¶
# Check if MCP server is running
curl http://localhost:3000/health
# Check logs
tail -f ~/.netintel-ocr/logs/mcp-server.log
# Restart with debug mode
netintel-ocr server mcp --debug --port 3000
2. Tool Timeout¶
// Increase timeout for long-running operations
const result = await mcp.callTool("kg_cypher_query", {
query: "MATCH (n) RETURN n", // Large query
timeout: 60000 // 60 seconds
});
3. Resource Not Found¶
// Check resource availability before access
const resources = await mcp.listResources();
if (resources.includes("kg://explore/main")) {
const kg = await mcp.readResource("kg://explore/main");
}
Performance Optimization¶
1. Connection Pooling¶
// Configure connection pool
const mcpConfig = {
connection: {
pool: {
min: 2,
max: 10,
idle: 30000
}
}
};
2. Parallel Tool Execution¶
// Execute tools in parallel when possible
const [entities, paths, stats] = await Promise.all([
mcp.callTool("extract_entities", { document_id: "doc_123" }),
mcp.callTool("kg_find_paths", { start: "A", end: "B" }),
mcp.callTool("get_collection_stats", { collection_name: "docs" })
]);
3. Streaming Results¶
// Stream large results
const stream = await mcp.streamTool("milvus_vector_search", {
collection_name: "large_collection",
query_vector: vector,
top_k: 1000,
stream: true
});
for await (const chunk of stream) {
processChunk(chunk);
}
Security Considerations¶
1. Authentication¶
// Configure MCP with authentication
const mcp = new MCPClient({
url: "http://localhost:3000",
auth: {
type: "api_key",
key: process.env.MCP_API_KEY
}
});
2. Input Validation¶
// Validate inputs before MCP calls
function validateMCPInput(tool, params) {
const schema = getToolSchema(tool);
for (const [key, value] of Object.entries(params)) {
if (!schema[key]) {
throw new Error(`Unknown parameter: ${key}`);
}
if (!validateType(value, schema[key].type)) {
throw new Error(`Invalid type for ${key}: expected ${schema[key].type}`);
}
if (schema[key].pattern && !new RegExp(schema[key].pattern).test(value)) {
throw new Error(`Invalid format for ${key}`);
}
}
return true;
}
3. Rate Limiting¶
// Implement client-side rate limiting
class RateLimiter {
constructor(maxRequests = 100, windowMs = 60000) {
this.maxRequests = maxRequests;
this.windowMs = windowMs;
this.requests = [];
}
async checkLimit() {
const now = Date.now();
this.requests = this.requests.filter(t => now - t < this.windowMs);
if (this.requests.length >= this.maxRequests) {
const oldestRequest = this.requests[0];
const waitTime = this.windowMs - (now - oldestRequest);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
this.requests.push(now);
}
}
Next Steps¶
- Explore API v2: See the API v2 Guide
- Learn Milvus: Read the Milvus Vector Database Guide
- Deploy to Production: Follow the Production Deployment Guide