Skip to main content
wit’s AI capabilities are built on a comprehensive set of tools that agents use to interact with repositories, understand code, and perform operations. This document provides a complete reference for developers who want to understand, use, or extend the tool system.

Overview

Tools are the building blocks that give AI agents their capabilities. Each tool is a discrete operation with:
  • Input Schema: Validated parameters using Zod
  • Output Schema: Typed return values
  • Execute Function: The implementation logic

Tool Categories

CategoryCountPurpose
Git Operations10Repository state and history
File System5Read, write, edit files
AI Generation4PR descriptions, reviews, release notes
Search3Pattern and semantic search
Virtual Filesystem6In-memory operations for IDE/server

How Tools are Used

Agents autonomously decide which tools to use based on the task. For example, when asked to “fix the bug in auth.ts”, the Code Agent might:
  1. getStatus - Check repository state
  2. readFile - Read auth.ts to understand the code
  3. editFile - Make the fix
  4. runCommand - Run tests to verify
  5. stageFiles - Stage the change
  6. createCommit - Commit with a descriptive message

Git Operations Tools

These tools provide access to Git functionality for reading repository state, making changes, and managing branches.

getStatus

Get the current status of the repository including staged, modified, and untracked files.
path
string
Path to the repository. Defaults to current directory.
Returns:
FieldTypeDescription
branchstring | nullCurrent branch name
stagedstring[]Files staged for commit
modifiedstring[]Modified but not staged
untrackedstring[]New untracked files
deletedstring[]Deleted files
hasChangesbooleanWhether any changes exist
isCleanbooleanWhether working tree is clean
Example:
const result = await tools.getStatus.execute({});
// {
//   branch: "feature/auth",
//   staged: ["src/auth.ts"],
//   modified: ["src/utils.ts"],
//   untracked: ["src/new-file.ts"],
//   deleted: [],
//   hasChanges: true,
//   isClean: false
// }

getDiff

Get the diff showing what has changed in the repository.
staged
boolean
default:false
If true, show only staged changes.
files
string[]
Specific files to show diff for. If not specified, shows all.
contextLines
number
default:3
Number of context lines around changes.
Returns:
FieldTypeDescription
diffsArrayPer-file diff information
diffs[].filestringFile path
diffs[].additionsnumberLines added
diffs[].deletionsnumberLines removed
diffs[].contentstringUnified diff content
totalAdditionsnumberTotal lines added
totalDeletionsnumberTotal lines removed
filesChangednumberNumber of files changed
summarystringHuman-readable summary
Example:
const result = await tools.getDiff.execute({ staged: true });
// {
//   diffs: [{
//     file: "src/auth.ts",
//     additions: 5,
//     deletions: 2,
//     content: "--- a/src/auth.ts\n+++ b/src/auth.ts\n@@ -10,7 +10,10 @@..."
//   }],
//   totalAdditions: 5,
//   totalDeletions: 2,
//   filesChanged: 1,
//   summary: "1 file(s) changed, 5 insertion(s), 2 deletion(s)"
// }

stageFiles

Stage files for the next commit.
files
string[]
required
Array of file paths to stage. Use ["."] to stage all files.
Returns:
FieldTypeDescription
successbooleanWhether staging succeeded
stagedFilesstring[]Files that were staged
messagestringStatus message
Example:
// Stage specific files
await tools.stageFiles.execute({ files: ["src/auth.ts", "src/utils.ts"] });

// Stage all files
await tools.stageFiles.execute({ files: ["."] });

createCommit

Create a new commit with staged changes.
message
string
required
The commit message describing the changes.
all
boolean
default:false
Stage all tracked modified files before committing (like git commit -a).
Returns:
FieldTypeDescription
successbooleanWhether commit succeeded
hashstringFull commit hash
shortHashstringShort (8 char) hash
branchstring | nullBranch name
messagestringStatus message
filesCommittednumberNumber of files in commit
Example:
const result = await tools.createCommit.execute({
  message: "feat(auth): add token refresh logic",
  all: true
});
// {
//   success: true,
//   hash: "abc123def456789...",
//   shortHash: "abc123de",
//   branch: "feature/auth",
//   message: "[feature/auth abc123de] feat(auth): add token refresh logic",
//   filesCommitted: 2
// }

getLog

Get the commit history.
limit
number
default:10
Maximum number of commits to return.
ref
string
default:"HEAD"
Starting reference (branch, tag, or commit hash).
Returns:
FieldTypeDescription
commitsArrayArray of commit objects
commits[].hashstringFull commit hash
commits[].shortHashstringShort hash
commits[].messagestringFull message
commits[].subjectstringFirst line of message
commits[].authorstringAuthor name
commits[].emailstringAuthor email
commits[].datestringISO date string
commits[].timestampnumberUnix timestamp
totalShownnumberNumber of commits returned

getBranches

List all branches in the repository. Input: None required Returns:
FieldTypeDescription
currentstring | nullCurrent branch name
branchesArrayList of branches
branches[].namestringBranch name
branches[].isCurrentbooleanIs this the current branch
branches[].hashstringCommit hash branch points to
totalBranchesnumberTotal branch count

switchBranch

Switch to a different branch.
branch
string
required
Name of the branch to switch to.
create
boolean
default:false
Create the branch if it doesn’t exist.
Returns:
FieldTypeDescription
successbooleanWhether switch succeeded
previousBranchstring | nullBranch we switched from
currentBranchstringBranch we switched to
messagestringStatus message
wasCreatedbooleanWhether branch was newly created
workSavedbooleanWhether uncommitted work was auto-saved
wit automatically saves uncommitted work when switching branches (auto-stash).

getMergeConflicts

Get information about current merge conflicts. Input: None required Returns:
FieldTypeDescription
inProgressbooleanWhether merge is in progress
sourceBranchstringBranch being merged
targetBranchstringBranch being merged into
conflictsArrayConflicting files with regions
conflicts[].filestringFile path
conflicts[].regionsArrayConflict regions
conflicts[].oursContentstringOur version
conflicts[].theirsContentstringTheir version
resolvedstring[]Already resolved files
unresolvednumberCount of unresolved conflicts

resolveConflict

Resolve a merge conflict by providing resolved content.
file
string
required
Path to the conflicted file.
content
string
required
The resolved content to write.
markResolved
boolean
default:true
Whether to mark the file as resolved.
Returns:
FieldTypeDescription
successbooleanWhether resolution succeeded
messagestringStatus message
remainingConflictsnumberConflicts still to resolve
canCompletebooleanWhether merge can be completed

undo

Undo the last operation(s) using wit’s journal.
steps
number
default:1
Number of operations to undo.
dryRun
boolean
default:false
Preview what would be undone without actually undoing.
Returns:
FieldTypeDescription
successbooleanWhether undo succeeded
undoneArrayOperations that were undone
undone[].operationstringOperation type
undone[].descriptionstringWhat was done
undone[].timestampnumberWhen it was done
messagestringStatus message
wit maintains a journal of all operations, making undo actually reliable unlike git reflog.

File System Tools

These tools allow agents to read, write, and navigate the repository file system.

readFile

Read the contents of a file from the repository.
filePath
string
required
Path to the file relative to repository root.
startLine
number
Start reading from this line (1-indexed).
endLine
number
Stop reading at this line (inclusive).
Returns:
FieldTypeDescription
successbooleanWhether read succeeded
contentstringFile content (or base64 for binary)
isBinarybooleanWhether file is binary
lineCountnumberTotal lines in file
startLinenumberActual start line returned
endLinenumberActual end line returned
sizenumberFile size in bytes
errorMessagestringError message if failed
Example:
// Read entire file
const result = await tools.readFile.execute({ filePath: "src/auth.ts" });

// Read specific lines (useful for large files)
const result = await tools.readFile.execute({
  filePath: "src/auth.ts",
  startLine: 50,
  endLine: 100
});
Always read a file before editing it. Agents are instructed to follow this pattern.

writeFile

Create a new file or overwrite an existing file.
filePath
string
required
Path to the file relative to repository root.
content
string
required
Content to write to the file.
createDirectories
boolean
default:true
Create parent directories if they don’t exist.
Returns:
FieldTypeDescription
successbooleanWhether write succeeded
filePathstringPath where file was written
createdbooleanWhether this was a new file
sizenumberSize of written file in bytes
messagestringStatus message
previousContentstringPrevious content (for undo)
Security:
  • Cannot write to .wit or .git directories
  • Cannot write outside the repository

editFile

Make targeted edits to existing files using search and replace.
filePath
string
required
Path to the file relative to repository root.
edits
Array
required
Array of edit operations to apply in order.
edits[].oldText
string
required
The exact text to find (must match exactly including whitespace).
edits[].newText
string
required
The text to replace it with.
dryRun
boolean
default:false
Validate edits without applying them.
Returns:
FieldTypeDescription
successbooleanWhether all edits succeeded
filePathstringFile that was edited
editsAppliednumberNumber of successful edits
editResultsArrayPer-edit results
editResults[].indexnumberEdit index
editResults[].appliedbooleanWhether edit was applied
editResults[].errorMessagestringError if failed
messagestringStatus message
diffstringPreview of changes
Example:
const result = await tools.editFile.execute({
  filePath: "src/auth.ts",
  edits: [
    {
      oldText: "const token = getToken();",
      newText: "const token = await getToken();"
    },
    {
      oldText: "function validateUser(user) {",
      newText: "async function validateUser(user) {"
    }
  ],
  dryRun: true  // Preview first
});
Best Practices:
  • Include enough context in oldText to uniquely identify the location
  • Preserve exact whitespace and indentation
  • Use dryRun: true first if unsure
  • Make one logical change per edit when possible

listDirectory

List files and directories in the repository.
dirPath
string
default:"."
Directory path relative to repository root.
recursive
boolean
default:false
List subdirectories recursively.
maxDepth
number
default:3
Maximum depth for recursive listing (1-10).
includeHidden
boolean
default:false
Include hidden files (starting with .).
pattern
string
Filter by glob pattern (e.g., *.ts, src/**/*.js).
Returns:
FieldTypeDescription
successbooleanWhether listing succeeded
pathstringDirectory that was listed
entriesArrayDirectory entries
entries[].namestringFile/directory name
entries[].pathstringRelative path
entries[].type'file' | 'directory'Entry type
entries[].sizenumberFile size (for files)
totalFilesnumberTotal file count
totalDirectoriesnumberTotal directory count
truncatedbooleanWhether results were truncated

runCommand

Execute shell commands with safety restrictions.
command
string
required
The command to execute.
args
string[]
Command arguments as separate array items.
timeout
number
default:60000
Timeout in milliseconds (max 120000).
env
Record<string, string>
Additional environment variables.
Returns:
FieldTypeDescription
successbooleanWhether command succeeded
exitCodenumberProcess exit code
stdoutstringStandard output
stderrstringStandard error
errorMessagestringError message if failed
timedOutbooleanWhether command timed out
truncatedbooleanWhether output was truncated
durationnumberExecution time in ms
sandboxbooleanWhether ran in sandbox
Allowed Commands:
// Package managers
'npm', 'npx', 'yarn', 'pnpm', 'bun'

// Build tools
'node', 'tsc', 'tsx', 'vite', 'webpack', 'esbuild', 'rollup'

// Testing
'jest', 'vitest', 'mocha', 'pytest', 'cargo'

// Linting
'eslint', 'prettier', 'biome', 'rustfmt', 'black', 'ruff'

// Languages
'python', 'python3', 'ruby', 'go', 'rustc'

// Utilities
'cat', 'ls', 'pwd', 'echo', 'head', 'tail', 'grep', 'find', 'wc', 'make', 'cmake'
Blocked Commands:
'rm', 'rmdir', 'sudo', 'su', 'curl', 'wget', 'ssh', 'chmod', 'kill', 'eval'
// ...and other dangerous commands
When sandbox is configured (E2B, Daytona, Docker, or Vercel), commands run in an isolated environment with fewer restrictions.

AI Generation Tools

These tools use AI to generate content like PR descriptions, code reviews, and release notes.

generatePRDescription

Generate a pull request description from diff and commits.
diff
string
required
The diff content showing code changes.
commits
Array
required
Commits included in the PR.
commits[].message
string
required
Commit message.
commits[].sha
string
required
Commit SHA.
title
string
Optional title (generated if not provided).
existingDescription
string
Existing description to enhance.
Returns:
FieldTypeDescription
titlestringPR title
descriptionstringFull markdown description
labelsstring[]Suggested labels
summarystringBrief summary
changesstring[]List of changes
testPlanstringSuggested test plan
breakingChangesstring[]Breaking changes if any

reviewPR

Perform an AI-powered code review.
diff
string
required
The diff content to review.
files
Array
Full file contents for deeper analysis.
context
object
Additional context for the review.
context.repoDescription
string
Description of the repository.
context.styleguide
string
Style guide to follow.
Returns:
FieldTypeDescription
summarystringReview summary
issuesArrayFound issues
issues[].severity'info' | 'warning' | 'error'Issue severity
issues[].filestringFile path
issues[].linenumberLine number
issues[].messagestringIssue description
issues[].suggestionstringSuggested fix
suggestionsstring[]General suggestions
securityConcernsstring[]Security issues
overallScorenumberScore 1-10
approvedbooleanWhether to approve
Checks Performed:
  • SQL injection vulnerabilities
  • Hardcoded secrets
  • XSS risks
  • Empty catch blocks
  • Console.log statements
  • Performance issues
  • Code style

generateReleaseNotes

Generate release notes from commits between versions.
version
string
required
The version being released (e.g., “v1.2.0”).
previousVersion
string
Previous version to compare against.
commits
Array
required
Commits included in this release.
style
'standard' | 'detailed' | 'minimal' | 'changelog'
default:"standard"
Output style.
Returns:
FieldTypeDescription
versionstringRelease version
titlestringRelease title
bodystringFull markdown body
categories.breakingArrayBreaking changes
categories.featuresArrayNew features
categories.fixesArrayBug fixes
categories.improvementsArrayImprovements
categories.documentationArrayDoc changes
categories.dependenciesArrayDependency updates
contributorsstring[]Contributors
statsobjectStatistics

Search Tools

Search the repository for commits, files, and content.
query
string
required
Search query (text pattern or regex).
searchCommits
boolean
default:true
Search in commit messages.
searchFiles
boolean
default:true
Search in file names.
searchContent
boolean
default:true
Search in file contents.
caseSensitive
boolean
default:false
Case-sensitive search.
maxResults
number
default:20
Maximum results to return.
filePattern
string
Glob pattern to filter files (e.g., *.ts).
Returns:
FieldTypeDescription
commitsArrayMatching commits
filesArrayMatching file names
contentArrayContent matches with line numbers
totalResultsnumberTotal matches
searchTimenumberTime in ms

semanticSearch

Search the codebase using natural language queries.
query
string
required
Natural language description (e.g., “function that handles user authentication”).
limit
number
default:10
Maximum number of results.
minSimilarity
number
Minimum similarity threshold (0-1).
pathPattern
string
Filter results to files matching this pattern.
language
string
Filter by programming language.
Returns:
FieldTypeDescription
resultsArrayMatching code chunks
results[].pathstringFile path
results[].startLinenumberStart line
results[].endLinenumberEnd line
results[].contentstringCode content
results[].scorenumberSimilarity score
results[].chunkTypestringType (function, class, etc.)
results[].chunkNamestringName if available
results[].languagestringProgramming language
totalResultsnumberTotal matches
querystringOriginal query
searchTimenumberTime in ms
Example:
const result = await tools.semanticSearch.execute({
  query: "code that validates email addresses",
  limit: 5,
  minSimilarity: 0.7,
  language: "typescript"
});
// Returns semantically relevant code, not just keyword matches

indexRepository

Index the repository for semantic search.
force
boolean
default:false
Force reindex all files.
include
string[]
File patterns to include.
exclude
string[]
File patterns to exclude.
Returns:
FieldTypeDescription
filesIndexednumberFiles that were indexed
filesSkippednumberFiles that were skipped
chunksCreatednumberCode chunks created
errorsCountnumberIndexing errors
durationnumberTime in ms
successbooleanWhether indexing succeeded
messagestringStatus message

getIndexStatus

Get the status of the semantic search index. Input: None required Returns:
FieldTypeDescription
vectorCountnumberNumber of vectors
fileCountnumberNumber of indexed files
dimensionsnumberVector dimensions
lastUpdatedstringLast update time
isReadybooleanWhether index is ready

Virtual Filesystem Tools

These tools work with an in-memory filesystem for the IDE and server-side operations. They allow editing files in bare repositories without a working directory.
Virtual filesystem tools require a sessionId parameter to identify the working session. Sessions are managed by the agent controller.

virtualReadFile (vfs-read-file)

Read a file from the virtual filesystem.
sessionId
string
required
Session ID for the virtual repository.
filePath
string
required
Path to the file.
startLine
number
Start reading from this line.
endLine
number
Stop reading at this line.

virtualWriteFile (vfs-write-file)

Write a file to the virtual filesystem.
sessionId
string
required
Session ID for the virtual repository.
filePath
string
required
Path to the file.
content
string
required
Content to write.
createDirectories
boolean
default:true
Create parent directories.

virtualEditFile (vfs-edit-file)

Edit a file using search and replace.
sessionId
string
required
Session ID for the virtual repository.
filePath
string
required
Path to the file.
Text to find.
replace
string
required
Text to replace with.
replaceAll
boolean
default:false
Replace all occurrences.

virtualListDirectory (vfs-list-directory)

List files in the virtual filesystem.
sessionId
string
required
Session ID for the virtual repository.
dirPath
string
default:"."
Directory path.
recursive
boolean
default:false
List recursively.
includeHidden
boolean
default:false
Include hidden files.

virtualCommit (vfs-commit)

Commit changes from the virtual filesystem.
sessionId
string
required
Session ID for the virtual repository.
message
string
required
Commit message.
authorName
string
Author name.
authorEmail
string
Author email.

virtualStatus (vfs-status)

Get the status of changes in the virtual filesystem.
sessionId
string
required
Session ID for the virtual repository.
Returns:
FieldTypeDescription
successbooleanWhether succeeded
branchstringCurrent branch
changesArrayChanged files
changes[].pathstringFile path
changes[].status'added' | 'modified' | 'deleted' | 'untracked'Change type
hasChangesbooleanWhether there are changes

Tool Registry

Tools are organized into bundles for different use cases:

witTools (Disk-based)

The main tool bundle for CLI and disk-based operations:
import { witTools } from 'wit/ai/tools';

// All 23 disk-based tools
const tools = witTools;
// tools.getStatus
// tools.getDiff
// tools.stageFiles
// tools.createCommit
// tools.getLog
// tools.getBranches
// tools.switchBranch
// tools.getMergeConflicts
// tools.resolveConflict
// tools.undo
// tools.search
// tools.semanticSearch
// tools.indexRepository
// tools.getIndexStatus
// tools.generatePRDescription
// tools.reviewPR
// tools.generateReleaseNotes
// tools.readFile
// tools.writeFile
// tools.editFile
// tools.listDirectory
// tools.runCommand
// tools.createBranch
// tools.openPullRequest

virtualTools (In-memory)

Tools for the IDE and server-side operations:
import { virtualTools } from 'wit/ai/tools';

// All 6 virtual filesystem tools
const tools = virtualTools;
// tools.readFile (vfs-read-file)
// tools.writeFile (vfs-write-file)
// tools.editFile (vfs-edit-file)
// tools.listDirectory (vfs-list-directory)
// tools.commit (vfs-commit)
// tools.status (vfs-status)

Creating Custom Tools

You can create custom tools to extend agent capabilities:
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

export const myCustomTool = createTool({
  // Unique identifier
  id: 'wit-my-custom-tool',

  // Description helps the AI understand when to use this tool
  description: `A clear description of what this tool does.
Include examples of when to use it.`,

  // Input validation with Zod
  inputSchema: z.object({
    requiredParam: z.string().describe('Description of this parameter'),
    optionalParam: z.number().optional().default(10).describe('Optional with default'),
    arrayParam: z.array(z.string()).optional().describe('Array of strings'),
  }),

  // Output schema for type safety
  outputSchema: z.object({
    success: z.boolean(),
    data: z.string().optional(),
    errorMessage: z.string().optional(),
  }),

  // The implementation
  execute: async ({ requiredParam, optionalParam, arrayParam }) => {
    try {
      // Your tool logic here
      const result = await doSomething(requiredParam, optionalParam);

      return {
        success: true,
        data: result,
      };
    } catch (error) {
      return {
        success: false,
        errorMessage: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  },
});

Registering Custom Tools

Add your tool to an agent:
import { Agent } from '@mastra/core/agent';
import { witTools } from 'wit/ai/tools';
import { myCustomTool } from './my-custom-tool';

const customAgent = new Agent({
  id: 'my-custom-agent',
  name: 'Custom Agent',
  instructions: '...',
  model: 'anthropic/claude-sonnet-4-20250514',
  tools: {
    ...witTools,
    myCustomTool,
  },
});

Best Practices for Custom Tools

  1. Clear descriptions: The AI uses descriptions to decide which tool to use
  2. Validate inputs: Use Zod schemas thoroughly
  3. Handle errors gracefully: Return error messages, don’t throw
  4. Security first: Validate paths, sanitize inputs
  5. Consistent output: Always include success and optional errorMessage
  6. Idempotent when possible: Same inputs should produce same outputs

Example: Agent Tool Interaction

Here’s how an agent uses tools to complete a task:
// User: "Add input validation to the createUser function"

// Agent's internal reasoning and tool calls:

// 1. First, understand the codebase structure
const dirResult = await tools.listDirectory.execute({
  dirPath: 'src',
  recursive: true,
  pattern: '*.ts'
});
// Found: src/services/user.ts

// 2. Read the file to understand current code
const fileResult = await tools.readFile.execute({
  filePath: 'src/services/user.ts'
});
// Read 150 lines, found createUser function at line 45

// 3. Make the edit
const editResult = await tools.editFile.execute({
  filePath: 'src/services/user.ts',
  edits: [{
    oldText: `function createUser(data: UserInput) {
  const user = new User(data);`,
    newText: `function createUser(data: UserInput) {
  // Validate input
  if (!data.email || !isValidEmail(data.email)) {
    throw new ValidationError('Invalid email address');
  }
  if (!data.name || data.name.length < 2) {
    throw new ValidationError('Name must be at least 2 characters');
  }

  const user = new User(data);`
  }]
});
// Edit applied successfully

// 4. Run tests to verify
const testResult = await tools.runCommand.execute({
  command: 'npm',
  args: ['test', '--', '--grep', 'createUser']
});
// Tests passed

// 5. Stage and commit
await tools.stageFiles.execute({ files: ['src/services/user.ts'] });
await tools.createCommit.execute({
  message: 'feat(user): add input validation to createUser'
});

See Also