# 🔧 Dynamic MCP Tool Creation Guide

## For AI Developers: Create Any MCP Tool Instantly

This guide shows how to create custom MCP tools on-the-fly using md-mcp server and Fabric-style markdown specifications.

---

## 🎯 Quick Start

**Create a new MCP tool in 3 steps:**

1. **Write a markdown specification** (Fabric pattern format)
2. **Use md-mcp's `forge_reality` function** to create the tool
3. **Tool is immediately available** via MCP

---

## 📝 Markdown Tool Specification Format

Based on Daniel Miessler's Fabric framework, extended for MCP:

```markdown
# IDENTITY and PURPOSE

[Clear description of what the tool does and its role]

# PARAMETERS

- param_name: type - Description
- optional_param: type (optional) - Description with defaults

# STEPS

1. First processing step
2. Second processing step
3. Final output generation

# OUTPUT

[Expected output format with examples]

```json
{
  "field": "value",
  "status": "success"
}
```

# EXAMPLES

- Input X → Output Y
- Edge case handling
- Error scenarios

# USAGE

[When and how to use this tool effectively]
```

---

## 🚀 Creating Tools with md-mcp

### Method 1: Using `forge_reality` Function

```javascript
// Create tool via MCP
await mcp.call('md-mcp', 'forge_reality', {
  divine_title: 'JSON Validator Tool',
  primal_essence: `# IDENTITY and PURPOSE
You are a JSON validation tool...
[full specification]`,
  creation_ritual: 'basic',
  mystical_properties: {
    tool_type: 'validator',
    dynamic: true
  }
});
```

### Method 2: Direct Filesystem

```bash
# Create tool file
cat > ~/mcp-tools/my-tool.md << 'EOF'
# IDENTITY and PURPOSE
Your tool spec here...
EOF
```

### Method 3: Using Claude Code

```
Use the mcp__md-mcp__forge_reality tool to create a new MCP tool:

Title: "SQL Query Optimizer"
Content: [paste your Fabric-format specification]
Ritual: basic
Properties: {"type": "database", "category": "optimization"}
```

---

## 🛠️ Tool Categories & Templates

### 1. **Validation Tools**

```markdown
# IDENTITY and PURPOSE
You validate [X] and provide detailed error reports.

# PARAMETERS
- input: string - Data to validate
- strict_mode: boolean (optional, default: false)

# STEPS
1. Parse input
2. Check against rules
3. Generate validation report

# OUTPUT
{
  "valid": boolean,
  "errors": [{"line": number, "message": string}],
  "warnings": [string]
}
```

**Examples:** JSON validator, YAML checker, regex tester

### 2. **Transformation Tools**

```markdown
# IDENTITY and PURPOSE
You transform [X format] to [Y format].

# PARAMETERS
- input: string - Source data
- output_format: string - Target format
- options: object - Transformation options

# STEPS
1. Parse source format
2. Apply transformations
3. Generate target format

# OUTPUT
{
  "transformed": string,
  "metadata": object
}
```

**Examples:** Markdown→HTML, JSON→YAML, CSV→SQL

### 3. **Analysis Tools**

```markdown
# IDENTITY and PURPOSE
You analyze [X] and provide insights about [Y].

# PARAMETERS
- data: string - Data to analyze
- depth: string - "shallow" | "deep"

# STEPS
1. Extract relevant information
2. Perform analysis calculations
3. Generate insights and recommendations

# OUTPUT
{
  "analysis": object,
  "insights": [string],
  "recommendations": [string],
  "confidence": number
}
```

**Examples:** Code complexity analyzer, performance profiler, security scanner

### 4. **Knowledge Retrieval Tools**

```markdown
# IDENTITY and PURPOSE
You retrieve and explain knowledge about [domain].

# PARAMETERS
- query: string - What to look up
- detail_level: string - "brief" | "detailed" | "expert"
- include_examples: boolean (default: true)

# STEPS
1. Parse query and identify key concepts
2. Retrieve relevant knowledge
3. Format response at appropriate detail level

# OUTPUT
{
  "answer": string,
  "sources": [string],
  "related_topics": [string],
  "examples": [object]
}
```

**Examples:** API reference lookup, protocol specification finder, algorithm explainer

---

## 📚 Real-World Examples

### Example 1: JSON Validator Tool

```markdown
# IDENTITY and PURPOSE

You are a JSON validation and formatting tool that validates JSON syntax,
formats it beautifully, and provides helpful error messages.

# PARAMETERS

- json_input: string - Raw JSON string to validate
- format_options: object (optional)
  - indent: number (default: 2)
  - sort_keys: boolean (default: false)
  - compact: boolean (default: false)

# STEPS

1. Parse the input JSON string
2. If invalid, identify exact error location and type
3. If valid, format according to options
4. Return formatted JSON or detailed error report

# OUTPUT

**On Success:**
{
  "valid": true,
  "formatted": "{\n  \"key\": \"value\"\n}",
  "stats": {"objects": 1, "arrays": 0, "keys": 1, "depth": 1}
}

**On Error:**
{
  "valid": false,
  "error": "Unexpected token } at position 15",
  "line": 3,
  "column": 5,
  "suggestion": "Missing comma after property"
}

# EXAMPLES

Input: `{"name":"John","age":30}`
Output: Formatted with 2-space indent

Input: `{"name":"John"age":30}`
Output: Error - Missing comma after "name" property

# USAGE

Perfect for:
- Validating API responses
- Formatting configuration files
- Debugging JSON syntax errors
```

### Example 2: Regex Pattern Tester

```markdown
# IDENTITY and PURPOSE

You are a regex testing and explanation tool that helps developers test
regular expressions, understand patterns, and debug matching issues.

# PARAMETERS

- pattern: string - Regular expression pattern
- test_string: string - Text to test against pattern
- flags: string (optional) - Regex flags (g, i, m, s, u, y)
- mode: string - "match" | "replace" | "split" | "explain"

# STEPS

1. Validate the regex pattern syntax
2. Apply pattern to test string based on mode
3. Extract matches with groups and positions
4. If explain mode, break down pattern components

# OUTPUT

**Match Mode:**
{
  "matches": ["match1", "match2"],
  "groups": [[0, 5], [10, 15]],
  "total": 2
}

**Explain Mode:**
{
  "pattern": "\\d{3}-\\d{4}",
  "explanation": [
    {"component": "\\d{3}", "meaning": "Exactly 3 digits"},
    {"component": "-", "meaning": "Literal hyphen"}
  ]
}

# USAGE

Perfect for testing regex before production use and learning regex syntax.
```

---

## 🎓 Best Practices

### 1. **Clear Purpose Definition**

```markdown
# IDENTITY and PURPOSE

❌ BAD: "You are a helper tool"
✅ GOOD: "You are a SQL query optimizer that analyzes queries for
          performance issues and suggests index improvements"
```

### 2. **Well-Defined Parameters**

```markdown
# PARAMETERS

❌ BAD:
- input: string

✅ GOOD:
- query: string - SQL SELECT statement to optimize
- database_type: string - "postgresql" | "mysql" | "sqlite"
- explain_plan: boolean (optional, default: false) - Include execution plan analysis
```

### 3. **Structured Output**

```markdown
# OUTPUT

❌ BAD: "Returns a result"

✅ GOOD:
{
  "optimized_query": string,
  "improvements": [
    {"type": "index", "table": "users", "columns": ["email"], "impact": "high"}
  ],
  "estimated_speedup": "3.2x",
  "warnings": [string]
}
```

### 4. **Practical Examples**

```markdown
# EXAMPLES

❌ BAD: "Works with data"

✅ GOOD:
Input: SELECT * FROM users WHERE email = 'test@example.com'
Output: {
  "optimized_query": "SELECT id, name FROM users WHERE email = ?",
  "improvements": [
    {"type": "select_list", "impact": "medium", "reason": "Avoid SELECT *"},
    {"type": "index", "columns": ["email"], "impact": "high"}
  ]
}
```

---

## 🔄 Dynamic Tool Workflow

### For AI Developers Using Claude Code:

```
User: "I need to validate YAML files"

AI: Let me create a YAML validator tool for you using md-mcp.

[Uses mcp__md-mcp__forge_reality with YAML validator specification]

Tool created! You can now use it like this:
mcp.call('yaml-validator', {yaml_input: "key: value"})
```

### Workflow Diagram:

```
1. AI identifies need for new tool
2. AI generates Fabric-format markdown spec
3. AI calls mcp__md-mcp__forge_reality
4. Tool is created and immediately available
5. AI can use tool for current task
6. Tool persists for future use
```

---

## 📦 Tool Storage & Organization

### Recommended Structure:

```
~/mcp-tools/
├── validators/
│   ├── json_validator.md
│   ├── yaml_validator.md
│   └── xml_validator.md
├── transformers/
│   ├── markdown_to_html.md
│   └── csv_to_json.md
├── analyzers/
│   ├── code_complexity.md
│   └── security_scanner.md
└── knowledge/
    ├── api_reference.md
    └── protocol_finder.md
```

### Integration with fr3ksik:

```bash
# Tools are automatically discovered from:
~/.config/fabric/patterns/     # Fabric patterns
~/mcp-tools/                   # Custom MCP tools
~/mi/md-mcp-tools/            # WikiFR3K tools (470+ patterns)
```

---

## 🧪 Testing Your Tools

### Validation Checklist:

```markdown
- [ ] Tool has clear IDENTITY and PURPOSE
- [ ] All PARAMETERS are documented with types
- [ ] STEPS outline the processing logic
- [ ] OUTPUT format is clearly specified
- [ ] EXAMPLES show realistic use cases
- [ ] USAGE explains when to use the tool
- [ ] Markdown syntax is valid
- [ ] No security issues (scripts, iframes, etc.)
```

### Using md-mcp validation:

```javascript
// Validate tool specification
const result = await mcp.call('md-mcp', 'divine_truth', {
  sacred_text: toolMarkdown,
  examine_symbols: true,
  test_connections: true
});

// Result shows:
// - isValid: boolean
// - errors: [...]
// - warnings: [...]
// - stats: {headers, paragraphs, codeBlocks, links}
```

---

## 🚀 Quick Reference Card

| Task | Method | Example |
|------|--------|---------|
| **Create tool** | `forge_reality` | Title, content, ritual |
| **Validate tool** | `divine_truth` | Pass markdown spec |
| **List tools** | `see_destiny` | Get available tools |
| **Read tool** | `read_fate` | Get tool specification |
| **Convert to HTML** | `weave_spells` | Render markdown |

---

## 💡 Pro Tips

1. **Start with Fabric patterns** - 500+ proven templates in wikifr3k
2. **Use clear naming** - `json_validator` not `validator`
3. **Document errors** - Show what happens when things go wrong
4. **Include examples** - Real-world use cases help understanding
5. **Test immediately** - Validate with `divine_truth` before deploying
6. **Version your tools** - Add version/date in frontmatter
7. **Categorize tools** - Organize by function (validators, analyzers, etc.)

---

## 🎯 Common Use Cases

### 1. On-Demand Validation

```
User: "Check if this JSON is valid"
AI: [Creates JSON validator tool if not exists, uses it immediately]
```

### 2. Domain-Specific Analysis

```
User: "Analyze this SQL query for performance"
AI: [Creates SQL analyzer tool, provides optimization recommendations]
```

### 3. Knowledge Retrieval

```
User: "What's the specification for HTTP/2?"
AI: [Creates protocol lookup tool, retrieves HTTP/2 spec]
```

### 4. Data Transformation

```
User: "Convert this CSV to JSON"
AI: [Creates CSV→JSON transformer, performs conversion]
```

---

## 📚 Additional Resources

- **Fabric Framework**: https://github.com/danielmiessler/fabric
- **WikiFR3K Tools**: ~/mi/md-mcp-tools/ (470+ patterns)
- **MCP Specification**: Model Context Protocol documentation
- **md-mcp Documentation**: Check `MD_MCP_COMPATIBILITY.md`

---

## ✨ Summary

**As an AI developer, you can now:**

1. ✅ Create any MCP tool you need instantly
2. ✅ Use Fabric-format markdown for tool specs
3. ✅ Validate tools with md-mcp functions
4. ✅ Build tools on-the-fly during conversations
5. ✅ Organize tools for reuse across projects
6. ✅ Leverage 470+ existing WikiFR3K patterns

**The power of dynamic MCP tool creation means you're never blocked by missing functionality - just create the tool you need!**

---

*Generated with fr3ksik v1.0.3 - Universal AI CLI Configuration System*
