tcl-mcp-server 0.1.2

A Model Context Protocol (MCP) server that provides TCL (Tool Command Language) execution capabilities with namespace-based tool management and versioning.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# bin__exec_tool Examples

This document provides comprehensive examples of using the `bin__exec_tool` functionality in the TCL MCP server.

## Overview

The `bin__exec_tool` is a system tool that allows execution of custom user-defined tools that have been added to the TCL MCP server. It provides a standardized way to invoke tools with parameters and handle their results.

## Basic Usage

### 1. Adding a Simple Tool

First, add a custom tool using `tcl_tool_add`:

```json
{
  "method": "tools/call",
  "params": {
    "name": "mcp__tcl__sbin___tcl_tool_add",
    "arguments": {
      "user": "alice",
      "package": "utils",
      "name": "greet",
      "description": "A friendly greeting tool",
      "script": "return \"Hello, $name! Welcome to TCL MCP.\"",
      "parameters": [
        {
          "name": "name",
          "description": "Name of the person to greet",
          "required": true,
          "type_name": "string"
        }
      ]
    }
  }
}
```

### 2. Executing the Tool

Now execute it using `bin__exec_tool`:

```json
{
  "method": "tools/call",
  "params": {
    "name": "mcp__tcl__bin___exec_tool",
    "arguments": {
      "tool_path": "/alice/utils/greet:latest",
      "arguments": {
        "name": "Bob"
      }
    }
  }
}
```

Response:
```json
{
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Hello, Bob! Welcome to TCL MCP."
      }
    ]
  }
}
```

## Advanced Examples

### String Manipulation Tool

```tcl
# Tool definition
{
  "user": "alice",
  "package": "strings",
  "name": "manipulate",
  "description": "Advanced string manipulation",
  "script": "
    set result \"\"
    
    # Reverse the string
    if {$reverse} {
        set text [string reverse $text]
    }
    
    # Change case
    switch $case {
        \"upper\" { set text [string toupper $text] }
        \"lower\" { set text [string tolower $text] }
        \"title\" { set text [string totitle $text] }
    }
    
    # Repeat if specified
    if {[info exists repeat] && $repeat > 1} {
        set text [string repeat $text $repeat]
    }
    
    return $text
  ",
  "parameters": [
    {
      "name": "text",
      "description": "Text to manipulate",
      "required": true,
      "type_name": "string"
    },
    {
      "name": "reverse",
      "description": "Whether to reverse the string",
      "required": true,
      "type_name": "boolean"
    },
    {
      "name": "case",
      "description": "Case transformation (upper/lower/title/none)",
      "required": true,
      "type_name": "string"
    },
    {
      "name": "repeat",
      "description": "Number of times to repeat",
      "required": false,
      "type_name": "integer"
    }
  ]
}
```

Execution:
```json
{
  "tool_path": "/alice/strings/manipulate:latest",
  "arguments": {
    "text": "Hello World",
    "reverse": true,
    "case": "upper",
    "repeat": 2
  }
}
```

Result: `"DLROW OLLEHDLROW OLLEH"`

### Mathematical Calculator

```tcl
# Tool definition
{
  "user": "bob",
  "package": "math",
  "name": "calculator",
  "description": "Advanced mathematical operations",
  "script": "
    # Define mathematical functions
    proc factorial {n} {
        if {$n <= 1} { return 1 }
        return [expr {$n * [factorial [expr {$n - 1}]]}]
    }
    
    proc fibonacci {n} {
        if {$n <= 1} { return $n }
        return [expr {[fibonacci [expr {$n - 1}]] + [fibonacci [expr {$n - 2}]]}]
    }
    
    proc gcd {a b} {
        while {$b != 0} {
            set temp $b
            set b [expr {$a % $b}]
            set a $temp
        }
        return $a
    }
    
    # Execute requested operation
    switch $operation {
        \"factorial\" { return [factorial $a] }
        \"fibonacci\" { return [fibonacci $a] }
        \"gcd\" { return [gcd $a $b] }
        \"power\" { return [expr {pow($a, $b)}] }
        \"sqrt\" { return [expr {sqrt($a)}] }
        default { error \"Unknown operation: $operation\" }
    }
  ",
  "parameters": [
    {
      "name": "operation",
      "description": "Mathematical operation to perform",
      "required": true,
      "type_name": "string"
    },
    {
      "name": "a",
      "description": "First number",
      "required": true,
      "type_name": "number"
    },
    {
      "name": "b",
      "description": "Second number (for binary operations)",
      "required": false,
      "type_name": "number"
    }
  ]
}
```

### Data Processing Tool

```tcl
# Tool definition for CSV processing
{
  "user": "data",
  "package": "processing",
  "name": "csv_stats",
  "description": "Calculate statistics from CSV data",
  "script": "
    # Parse CSV data
    set lines [split $csv_data \\n]
    set headers [split [lindex $lines 0] ,]
    set data_rows [lrange $lines 1 end]
    
    # Find column index
    set col_idx [lsearch $headers $column]
    if {$col_idx == -1} {
        error \"Column '$column' not found\"
    }
    
    # Extract column values
    set values {}
    foreach row $data_rows {
        if {$row ne \"\"} {
            set fields [split $row ,]
            set value [lindex $fields $col_idx]
            if {[string is double $value]} {
                lappend values $value
            }
        }
    }
    
    # Calculate statistics
    set count [llength $values]
    if {$count == 0} {
        return \"No numeric values found\"
    }
    
    set sum 0
    set min [lindex $values 0]
    set max [lindex $values 0]
    
    foreach val $values {
        set sum [expr {$sum + $val}]
        if {$val < $min} { set min $val }
        if {$val > $max} { set max $val }
    }
    
    set avg [expr {$sum / double($count)}]
    
    # Format result
    set result \"\"
    append result \"Count: $count\\n\"
    append result \"Sum: $sum\\n\"
    append result \"Average: [format %.2f $avg]\\n\"
    append result \"Min: $min\\n\"
    append result \"Max: $max\"
    
    return $result
  ",
  "parameters": [
    {
      "name": "csv_data",
      "description": "CSV data to process",
      "required": true,
      "type_name": "string"
    },
    {
      "name": "column",
      "description": "Column name to analyze",
      "required": true,
      "type_name": "string"
    }
  ]
}
```

### File Template Generator

```tcl
# Tool for generating file contents from templates
{
  "user": "dev",
  "package": "templates",
  "name": "generate",
  "description": "Generate file content from templates",
  "script": "
    # Define templates
    set templates [dict create]
    
    dict set templates \"python\" {
#!/usr/bin/env python3
\"\"\"
$description
\"\"\"

import sys

def main():
    \"\"\"Main function.\"\"\"
    # TODO: Implement $name
    pass

if __name__ == \"__main__\":
    main()
}
    
    dict set templates \"javascript\" {
/**
 * $description
 */

'use strict';

/**
 * $name implementation
 */
function $name() {
    // TODO: Implement
}

module.exports = { $name };
}
    
    dict set templates \"dockerfile\" {
FROM $base_image

LABEL maintainer=\"$author\"
LABEL description=\"$description\"

WORKDIR /app

# Install dependencies
RUN apt-get update && apt-get install -y \\
    && rm -rf /var/lib/apt/lists/*

# Copy application
COPY . .

# Set entrypoint
ENTRYPOINT [\"/app/entrypoint.sh\"]
}
    
    # Get template
    if {![dict exists $templates $template_type]} {
        error \"Unknown template type: $template_type\"
    }
    
    set template [dict get $templates $template_type]
    
    # Substitute variables
    set result $template
    foreach {var value} [array get ::] {
        if {[string match \"*$var*\" $result]} {
            regsub -all \"\\$$var\" $result $value result
        }
    }
    
    return $result
  ",
  "parameters": [
    {
      "name": "template_type",
      "description": "Type of template (python/javascript/dockerfile)",
      "required": true,
      "type_name": "string"
    },
    {
      "name": "name",
      "description": "Name of the component",
      "required": true,
      "type_name": "string"
    },
    {
      "name": "description",
      "description": "Description of the component",
      "required": true,
      "type_name": "string"
    },
    {
      "name": "author",
      "description": "Author name (for dockerfile)",
      "required": false,
      "type_name": "string"
    },
    {
      "name": "base_image",
      "description": "Base image (for dockerfile)",
      "required": false,
      "type_name": "string"
    }
  ]
}
```

## Error Handling Examples

### 1. Missing Required Parameter

Request:
```json
{
  "tool_path": "/alice/utils/greet:latest",
  "arguments": {}  // Missing required 'name' parameter
}
```

Error Response:
```json
{
  "error": {
    "code": -32602,
    "message": "Missing required parameter: name"
  }
}
```

### 2. Tool Not Found

Request:
```json
{
  "tool_path": "/nonexistent/tool:1.0",
  "arguments": {}
}
```

Error Response:
```json
{
  "error": {
    "code": -32602,
    "message": "Tool '/nonexistent/tool:1.0' not found"
  }
}
```

### 3. Script Execution Error

When a tool's TCL script encounters an error:

```json
{
  "error": {
    "code": -32603,
    "message": "TCL execution error: invalid command name \"undefined_proc\""
  }
}
```

## Best Practices

1. **Parameter Validation**: Always define required parameters with appropriate types
2. **Error Handling**: Include error checking in your TCL scripts
3. **Documentation**: Provide clear descriptions for tools and parameters
4. **Versioning**: Use semantic versioning for your tools
5. **Namespacing**: Organize tools into logical packages
6. **Testing**: Test tools thoroughly before deployment

## Security Considerations

1. **Privileged Mode**: Some operations require the server to run in privileged mode
2. **Input Sanitization**: The server automatically escapes special characters in string parameters
3. **Resource Limits**: Consider implementing timeouts for long-running operations
4. **Access Control**: Use namespaces to organize and control access to tools

## Performance Tips

1. **Caching**: Tools are cached in memory for fast execution
2. **Async Operations**: The server handles concurrent requests efficiently
3. **Minimal Dependencies**: Keep TCL scripts lightweight
4. **Batch Operations**: Design tools to handle multiple items when appropriate