DeepSeek Harness: Tool Usage

Last updated: 2026-08-31

Tools are the Agent's "hands and feet" — without tools, the Agent can only "talk the talk"; with tools, the Agent can read/write files, execute commands, search code, and make plans. DSH's tool system is built on the Cordis plugin architecture — every tool is a plugin, extensible, replaceable, and composable.

💡 Tip: DSH's tool system uses a three-stage pipeline — pre-execute (validation/approval) → execute (actual execution) → post-execute (log recording). Understanding this pipeline gives you full control over tool behavior.

📋 Prerequisites: Completed 05-modes.md, familiar with the four running modes

1. What You'll Learn


Tool Pipeline

2. Built-in Tool Overview

(1) ToolOverview

100%
graph TB
    subgraph DSHTools[DSH Built-in Tools]
        FE[file_edit<br/>File Read/Write & Edit]
        SH[shell<br/>Shell Command Execution]
        SR[search<br/>Code & File Search]
        SK[skills<br/>Skill Invocation]
        PL[plan<br/>Plan Creation & Tracking]
        SB[sandbox<br/>Sandbox Environment Management]
    end

(2) Tool Function Comparison

Tool Function Security Level Requires Approval
file_edit Create, read, edit, delete files 🔴 High Yes
shell Execute Shell commands 🔴 High Yes
search Search files and code content 🟢 Low No
skills Invoke predefined skill templates 🟡 Medium Depends
plan Create and track execution plans 🟢 Low No
sandbox Manage sandbox environment 🟡 Medium Yes

3. file_edit — File Operation Tool

(1) Supported Operations

file_edit is the most commonly used tool, supporting four operations:

Operation Description Approval Required
read Read file content No approval needed
create Create new file Approval required
edit Edit existing file Approval required
delete Delete file Approval required

(2) Reading Files

▶ Example 1: Reading File Content

TYPESCRIPT
// Agent's file_edit call parameters
{
  action: "read",
  path: "src/config.ts",
  encoding: "utf-8"
}

After reading, the Agent automatically analyzes the file content:

TEXT 📖 Display only
🤖 Agent:
🔍 Using tool: file_edit (read)
  → Path: src/config.ts
  → Size: 1.2KB

This configuration file exports three settings:
- DATABASE_URL: Database connection string
- PORT: Service port (default 3000)
- LOG_LEVEL: Log level (default info)

(3) Creating Files

▶ Example 2: Creating a New File

TYPESCRIPT
// Agent calls file_edit to create a file
{
  action: "create",
  path: "src/utils/logger.ts",
  content: "export function log(level: string, msg: string) {\n  const ts = new Date().toISOString();\n  console.log(`[${ts}] [${level}] ${msg}`);\n}"
}

Creating a file triggers an approval popup; the file is only written after user confirmation.

(4) Editing Files

▶ Example 3: Editing a File (diff mode)

DSH file editing uses diff mode, only modifying the parts that need to change:

TYPESCRIPT
// Agent calls file_edit to edit a file
{
  action: "edit",
  path: "src/app.ts",
  changes: [
    {
      type: "insert",
      line: 5,
      content: "import { log } from './utils/logger';"
    },
    {
      type: "replace",
      line: 23,
      oldContent: "console.log('Server started');",
      newContent: "log('info', 'Server started');"
    }
  ]
}

The approval popup displays a diff view:

TEXT 📖 Display only
⚠️ Approval Required: Edit file src/app.ts

  +5 | import { log } from './utils/logger';
  
  -23| console.log('Server started');
  +23| log('info', 'Server started');

  [Allow] [Always] [Deny]

(5) Reversible Editing

All file_edit modifications are reversible. DSH automatically saves a file snapshot before editing:

100%
graph LR
    A[Pre-edit Snapshot] --> B[Apply Edits]
    B --> C[Post-edit State]
    C -->|Rollback| A

4. shell — Shell Command Tool

(1) Basic Usage

▶ Example 4: Executing a Safe Command

TYPESCRIPT
// Agent executes ls command
{
  command: "ls -la src/",
  cwd: "/home/alice/project",
  timeout: 30000
}

(2) Command Security Classification

DSH classifies Shell commands by danger level:

Level Command Examples Approval Policy
Safe ls, cat, grep, head, wc Auto-allow
Moderate npm install, git add, mkdir Approval required
Dangerous rm, chmod, sudo, dd Approval + confirmation required
Forbidden rm -rf /, mkfs, > /dev/sda Auto-deny

▶ Example 5: Executing a Moderate-Risk Command

TYPESCRIPT
// Agent executes npm view (view package info, moderate risk)
{
  command: "npm view jsonwebtoken",
  cwd: "/home/alice/project",
  timeout: 120000
}

Approval popup:

TEXT 📖 Display only
⚠️ Approval Required: Execute shell command

  Command: npm view jsonwebtoken
  Working directory: /home/alice/project
  Estimated packages: 1

  [Allow] [Always for npm] [Deny]

(3) Timeout and Interruption

TYPESCRIPT
// Shell tool parameters
interface ShellParams {
  command: string;
  cwd?: string;
  timeout?: number;      // Timeout in milliseconds, default 30000
  env?: Record<string, string>;  // Additional environment variables
}

Long-running commands will be interrupted by timeout:

TEXT 📖 Display only
🤖 Agent:
🔧 Using tool: shell
  → Command: npm run build
  → Timeout: 120000ms

⏱️ Build completed in 45s
  → Output: Build successful. 15 files generated.

5. search — Search Tool

(1) Search Modes

The search tool supports multiple search modes:

Mode Description Example
File Search Find by filename/path *.test.ts
Content Search Search by content regex import.*from
Symbol Search Search function/class definitions class UserService

▶ Example 6: Searching Files

TYPESCRIPT
// Search for all test files
{
  pattern: "*.test.ts",
  type: "file",
  maxResults: 50
}

▶ Example 7: Searching Code Content

TYPESCRIPT
// Search for all import statements
{
  pattern: "import.*from 'express'",
  type: "content",
  filePattern: "*.ts",
  maxResults: 100
}

(2) Search Results Display

TEXT 📖 Display only
🤖 Agent:
🔍 Using tool: search
  → Pattern: import.*from 'express'
  → Type: content
  → Results: 8 matches

Found in:
  src/app.ts:1         — import express from 'express';
  src/routes/users.ts:3 — import express from 'express';
  src/routes/auth.ts:2  — import express from 'express';
  ...

6. skills — Skill Tool

(1) Concept of Skills

Skills are predefined task templates that encapsulate complete workflows for common operations:

100%
graph LR
    USER[User Request] --> SK[Skill Template]
    SK --> T1[Tool Call 1]
    SK --> T2[Tool Call 2]
    SK --> T3[Tool Call 3]

(2) Built-in Skills

Skill Description Included Operations
add-test Add tests for a function search → file_edit (create)
refactor Extract functions/classes file_edit (read) → file_edit (edit × N)
debug Debug errors search → shell → file_edit
document Add documentation comments file_edit (read) → file_edit (edit)

▶ Example 8: Invoking a Skill

TYPESCRIPT
// Invoke add-test skill
{
  skill: "add-test",
  params: {
    target: "src/utils/format.ts::formatDate",
    framework: "jest"
  }
}

7. plan — Plan Tool

(1) Creating and Tracking Plans

The plan tool is used to create and track execution plans for multi-step tasks:

▶ Example 9: Creating an Execution Plan

TYPESCRIPT
// Create a plan
{
  action: "create",
  steps: [
    { id: 1, desc: "Install dependencies", tool: "shell" },
    { id: 2, desc: "Create auth module", tool: "file_edit" },
    { id: 3, desc: "Update app.ts", tool: "file_edit" },
    { id: 4, desc: "Write tests", tool: "file_edit" },
    { id: 5, desc: "Run tests", tool: "shell" }
  ]
}

▶ Example 10: Updating Plan Status

TYPESCRIPT
// Mark step as complete
{
  action: "update",
  stepId: 1,
  status: "completed",
  result: "Installed jsonwebtoken, bcryptjs"
}

(2) Plan Tool and PTC Mode

The plan tool underlies PTC mode:

100%
graph TD
    PTC[PTC Mode] --> PLAN[plan Tool Creates Plan]
    PLAN --> USER[User Reviews]
    USER --> EXEC[Execute Steps Per Plan]
    EXEC --> UPDATE[plan Tool Updates Status]
    UPDATE --> DONE{All Complete?}
    DONE -->|No| EXEC
    DONE -->|Yes| REPORT[Output Summary]

8. Tool Execution Pipeline

(1) Three-Stage Pipeline

Every tool call goes through three stages:

100%
graph LR
    PRE[pre-execute<br/>Parameter Validation<br/>Permission Check<br/>Approval Popup] --> EXEC[execute<br/>Actual Execution<br/>Capture Output] --> POST[post-execute<br/>Log Recording<br/>Event Emission<br/>Status Update]

▶ Example 11: Pipeline Pseudocode

TYPESCRIPT
async function executeToolPipeline(tool: Tool, params: Params): Promise<Result> {
  // Stage 1: pre-execute
  const preResult = await preExecute(tool, params);
  if (preResult.denied) {
    throw new ToolDeniedError(preResult.reason);
  }

  // Stage 2: execute
  const result = await tool.execute(params);

  // Stage 3: post-execute
  await postExecute(tool, params, result);
  ctx.emit('tool.executed', { tool: tool.name, params, result });

  return result;
}

(2) pre-execute Stage

pre-execute handles validation and approval:

TYPESCRIPT
interface PreExecuteResult {
  allowed: boolean;
  reason?: string;
  modifiedParams?: Params;
}
Check Item Description
Parameter validation Whether parameter format and types are correct
Permission check Whether the user has permission to execute this operation
Approval popup Whether dangerous operations require user confirmation
Sandbox check Whether the operation is within the workspace scope

(3) post-execute Stage

post-execute handles recording and notification:

TYPESCRIPT
interface PostExecuteAction {
  log: boolean;           // Record to session log
  emit: boolean;          // Emit event
  updateTrajectory: boolean;  // Update Trajectory
  notifyUI: boolean;      // Notify Web UI update
}

9. Tool Approval Policy

(1) Policy Configuration

▶ Example 12: Approval Policy Configuration

YAML
# dsh.config.yaml
approval:
  # Global default policy
  default: ask

  # Per-tool settings
  tools:
    file_edit:
      read: always          # Reads always allowed
      create: ask           # Creates require approval
      edit: ask             # Edits require approval
      delete: ask_with_confirm  # Deletes require double confirmation
    
    shell:
      safe: always          # Safe commands always allowed
      moderate: ask         # Moderate commands require approval
      dangerous: deny       # Dangerous commands auto-denied
    
    search:
      default: always       # Search always allowed
    
    skills:
      default: ask          # Skill calls require approval
    
    plan:
      default: always       # Plans always allowed

(2) Approval Mode Descriptions

Mode Description Use Case
always Always allow, no popup Safe operations
ask Requires approval, popup confirmation Dangerous operations
ask_with_confirm Requires double confirmation Extremely dangerous operations
deny Auto-deny Operations that must never be allowed

10. Custom Tool Introduction

(1) Creating Custom Tools

DSH tools are Cordis plugins, written in TypeScript:

▶ Example 13: Custom HTTP Request Tool

TYPESCRIPT
import { definePlugin } from '@deepseek-ai/dsh';

export default definePlugin({
  name: 'tool-http-request',
  version: '1.0.0',
  contribute(ctx) {
    ctx.registerTool({
      name: 'http_request',
      description: 'Make HTTP requests to external APIs',
      parameters: {
        type: 'object',
        properties: {
          url: { type: 'string', description: 'Request URL' },
          method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE'] },
          headers: { type: 'object', description: 'Request headers' },
          body: { type: 'string', description: 'Request body' }
        },
        required: ['url', 'method']
      },
      async execute(params) {
        const response = await fetch(params.url, {
          method: params.method,
          headers: params.headers,
          body: params.body
        });
        return {
          status: response.status,
          body: await response.text()
        };
      }
    });
  }
});

(2) Registering Custom Tools

Place custom tool plugins in the project's .dsh/plugins/ directory:

TEXT 📖 Display only
.dsh/
└── plugins/
    └── tool-http-request/
        ├── index.ts
        └── package.json

Or specify in the configuration file:

YAML
# dsh.config.yaml
plugins:
  - path: "./custom-tools/http-request"
  - path: "./custom-tools/database-query"

(3) Custom Tool Approval

Custom tools also need to define approval policies:

TYPESCRIPT
ctx.registerTool({
  name: 'http_request',
  // ...
  approval: {
    level: 'ask',     // Default requires approval
    rules: [
      { match: { method: 'GET' }, level: 'always' },     // GET requests auto-allowed
      { match: { method: 'POST' }, level: 'ask' },       // POST requires approval
      { match: { method: 'DELETE' }, level: 'deny' }     // DELETE auto-denied
    ]
  }
});

❓ FAQ

Q How many tools does the Agent call at once?
A It depends on task complexity. Simple Q&A might not call any tools; complex tasks might call 5-10 tools in sequence. Standard mode has no upper limit; Minimal mode is limited to a maximum of 1.
Q What happens if a tool call fails?
A The Agent receives the error information and can automatically retry or adjust its strategy. After 3 consecutive failures, the Agent reports to the user and asks for guidance.
Q Can I disable a specific tool?
A Yes. Set tools.disabled: ["shell"] in the configuration file to disable specified tools.
Q What's the difference between search and grep in shell?
A search is DSH's built-in structured search that understands project directory structure and supports filename/content/symbol modes. shell grep is a general text search. We recommend using search first.
Q Can custom tools be written in Python?
A Currently the DSH plugin system only supports TypeScript. Python tools can be indirectly invoked through the shell tool by calling Python scripts.
Q Is there a concurrency limit on tool execution?
A DSH executes tools serially by default (one completes before the next starts). This is because tools may have dependencies on each other.

📖 Summary


📝 Exercises

1. ⭐ Basic: Use the DSH Agent to complete the following operations: 1) Use the search tool to find all TypeScript files in the project; 2) Use file_edit to read one of them. Record the parameters and results of both tool calls.

2. ⭐⭐ Intermediate: Configure approval policies so that file_edit read operations are auto-allowed, create/edit operations require approval, and delete operations require double confirmation. Test each operation to verify the approval policies are working.

3. ⭐⭐⭐ Challenge: Create a custom tool plugin that queries the latest 5 commits in the current Git repository (calling git log -5 --oneline), register it in DSH, and have the Agent successfully invoke it.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏