microsoft/garnet/add-garnet-command

Claude Code and agent skill by microsoft/garnet

Trust tier 4
  • vendor
Source check pending

Checking that the SKILL.md file is still in the repository.

Adds a new built-in RESP command to Garnet end-to-end. Covers enum registration, parsing, dispatch, RESP handler, API surface, storage session, RMW callbacks, command metadata JSON, ACL tests, and integration tests. Use when asked to "add a command", "implement RI.SET", "add RESP command", or any new server command. Do NOT use for custom extension commands (CustomRawStringFunctions) or object-type sub-operations.

Install

npx vskill@latest install microsoft/garnet/add-garnet-command

SKILL.md

The same SKILL.md was published earlier as microsoft/garnet/add-garnet-command.

Add a New Built-in RESP Command to Garnet

Step-by-step guide for implementing a new built-in RESP command in Garnet. This covers every file that must be created or modified, the tools that must be run, caveats discovered during implementation, and how to verify correctness.

Scope: Built-in commands that are part of the Garnet server (not custom extensions registered via REGISTERCS).


Overview: What Must Change

Adding a single new command touches at minimum these areas:

#AreaFilesRequired?
1RespCommand enumlibs/server/Resp/Parser/RespCommand.cs✅ Always
2Command parsinglibs/server/Resp/Parser/RespCommand.cs✅ Always
3Command dispatchlibs/server/Resp/RespServerSession.cs✅ Always
4RESP handlerlibs/server/Resp/<Category>/*.cs✅ Always
5API interfacelibs/server/API/IGarnetApi.csIf key-value command (not blocking/admin)
6API delegationlibs/server/API/GarnetApi*.csIf key-value command (not blocking/admin)
7Storage session`libs/server/Storage/Session/[Main\Object\Unified]Store/*Ops.cs`If key-value command (not blocking/admin)
8RMW/Read callbacks`libs/server/Storage/Functions/[Main\Unified]Store/[RMW\Read]Methods.cs`If string/unified command using RMW/Read
8bRead responselibs/server/Storage/Functions/MainStore/PrivateMethods.csIf string command using Read (add to CopyRespToWithInput)
9VarLen methods`libs/server/Storage/Functions/[Main\Unified]Store/VarLenInputMethods.cs`If string/unified command using RMW
10Object operation enumlibs/server/Objects/[ObjectName]/[ObjectName]Object.csIf new object sub-operation
11Object implementationlibs/server/Objects/[ObjectName]/[ObjectName]ObjectImpl.csIf new object sub-operation
12ItemBrokerlibs/server/Objects/ItemBroker/CollectionItemBroker.csIf blocking command
13Command info JSONlibs/resources/RespCommandsInfo.json✅ Always (generated)
14Command docs JSONlibs/resources/RespCommandsDocs.json✅ Always (generated)
15Supported commandsplayground/CommandInfoUpdater/SupportedCommand.cs✅ Always
16Garnet command infoplayground/CommandInfoUpdater/GarnetCommandsInfo.jsonIf Garnet-only command
17Garnet command docsplayground/CommandInfoUpdater/GarnetCommandsDocs.jsonIf Garnet-only command
18ACL testtest/Garnet.test/Resp/ACL/RespCommandTests.cs✅ Always
19Integration teststest/Garnet.test/Resp*.cs✅ Always
20Website documentationwebsite/docs/commands/✅ Always
21Configuration settingsOptions.cs, GarnetServerOptions.cs, defaults.confIf command is optional/gated

Step 1: Add the RespCommand Enum Value

File: libs/server/Resp/Parser/RespCommand.cs

The RespCommand enum is writes-first: write (mutating) commands occupy a dense, explicitly-numbered block immediately after NONE, followed by reads, scripts, and non-data:

Write commands: APPEND = 1 ... BITOP_DIFF = 120 (EXPLICIT values; the ONLY persisted values)
Read commands: BITCOUNT ... RISCAN (auto-numbered; never persisted)
Script commands: EVAL, EVALSHA (LastDataCommand = EVALSHA)
Non-key commands: PING, SUBSCRIBE, etc.
Admin commands: AUTH, CONFIG, etc.

Why writes-first: the write command's numeric value is persisted to disk (serialized into RespInputHeader.cmd in the AOF and streamed to replicas). Keeping writes in a dense, explicitly-numbered leading block makes those values stable — adding a read/admin command (which is never persisted) cannot shift them.

Read/write classification uses enum ranges (positional constants, not hardcoded values):

  • RespCommandExtensions.FirstWriteCommand (APPEND=1) .. LastWriteCommand (BITOP_DIFF=120) → write
  • FirstReadCommand .. LastReadCommand (= EVAL - 1) → read-only

Rules for adding a command:

  • Write (mutating) command: APPEND it at the end of the write block, immediately before

the // Read-only commands marker, with the next explicit value (e.g. MYCMD = 121,). Then update LastWriteCommand if it is no longer BITOP_DIFF. Never insert into the middle of the write block or change/reuse an existing value — persisted values must be append-only.

  • Read-only / script / non-data command: add it in the appropriate (auto-numbered) section.

These are never persisted, so their values may shift freely.

  • Adding a write shifts the auto-numbered reads up by one — that is harmless (reads aren't

persisted) and requires no other change.

Guardrails (do not bypass):

  • PersistedEnumStabilityTests snapshots the write-block values and asserts the write range

contains exactly the write commands. If you change an existing write value it fails — that is a breaking on-disk change requiring an AofHeader.AofHeaderVersion bump + a legacy remap in AofProcessor / LegacyRespCommand, not an edited expected value.

  • If a new write command's value ever approaches the custom command range (0xFEFF), that is also

caught by a test.

Boundary markers to watch (search for these comments):

csharp
APPEND = 1, // Note: FirstWriteCommand — keep as the first write command
BITOP_DIFF = 120, // Note: LastWriteCommand — append new write commands after this with the next value
EVALSHA, // Note: Update LastDataCommand if adding new data commands after this

Step 2: Add Command Parsing

File: libs/server/Resp/Parser/RespCommand.cs

Two parsing tiers exist:

Hash table path: RespCommandHashLookup (primary path for most commands)

The hash table in libs/server/Resp/Parser/RespCommandHashLookupData.cs provides O(1) lookup for all built-in commands. This is the recommended path for all new commands.

To add a new primary command, add one line to PopulatePrimaryTable() in RespCommandHashLookupData.cs:

csharp
Add("DELIFGREATER", RespCommand.DELIFGREATER);

To add a command with subcommands (e.g., MYPARENT SUBCMD):

  1. Add the parent with hasSub: true in PopulatePrimaryTable():

``csharp Add("MYPARENT", RespCommand.MYPARENT, hasSub: true); ``

  1. Define the subcommand array in RespCommandHashLookupData.cs:

``csharp private static readonly (string Name, RespCommand Command)[] MyparentSubcommands = [ ("SUBCMD1", RespCommand.MYPARENT_SUBCMD1), ("SUBCMD2", RespCommand.MYPARENT_SUBCMD2), ]; ``

  1. Build the table in the static constructor in RespCommandHashLookup.cs:

``csharp myparentSubTable = BuildSubTable(MyparentSubcommands, out myparentSubTableMask); ``

  1. Wire it into LookupSubcommand() in RespCommandHashLookup.cs:

``csharp RespCommand.MYPARENT => (myparentSubTable, myparentSubTableMask), ``

⚠️ Important: Use the exact wire-protocol spelling for the hash table name string. Some commands use hyphens (e.g., "SET-CONFIG-EPOCH" not "SETCONFIGEPOCH"). Check CmdStrings.cs for the canonical spelling.

⚠️ Convention: Define the command name string in `libs/server/Resp/CmdStrings.cs` and reference it from the parser, rather than using inline "..."u8 literals. This keeps command name strings centralized and reusable (e.g., for error messages).

csharp
// In CmdStrings.cs:
public static ReadOnlySpan<byte> DELIFGREATER => "DELIFGREATER"u8;
SIMD fast path: FastParseCommand() (optional, for hottest commands only)

Static Vector128<byte> patterns defined in libs/server/Resp/Parser/RespCommandSimdPatterns.cs that match the full RESP encoding (*N\r\n$L\r\nCMD\r\n) in a single 16-byte comparison. Use the RespPattern(argCount, "CMD") helper to create new patterns. Only needed for the most performance-critical commands with:

  • Fixed argument count (single digit)
  • Command names of 3-6 characters (total encoded length must fit in 16 bytes)

Most new commands should NOT be added here — the hash table + MRU cache provide excellent performance for all commands. Only add SIMD patterns if benchmarking shows the command is a bottleneck.


Step 3: Add Command Dispatch

File: libs/server/Resp/RespServerSession.cs

Three dispatch methods exist, and which one you use matters for latency tracking:

MethodForLatency
ProcessBasicCommandsFast single/dual-arg commands@fast only
ProcessArrayCommandsFast multi-arg commands@fast only
ProcessOtherCommandsSlow commands, admin commands@slow OK

⚠️ WARNING: Do NOT add @slow-classified commands to ProcessBasicCommands or ProcessArrayCommands. This breaks latency tracking. If in doubt, use ProcessOtherCommands.

Pattern:

csharp
RespCommand.MYCMD => NetworkMYCMD(ref storageApi),

Add before the _ => ... fallthrough in the appropriate method.


Step 4: Implement the RESP Handler

New file or existing file in libs/server/Resp/

Command handlers are methods on the RespServerSession partial class:

csharp
private bool NetworkMYCMD<TGarnetApi>(ref TGarnetApi storageApi)
where TGarnetApi : IGarnetApi
{
// 1. Validate argument count
if (parseState.Count != N)
return AbortWithWrongNumberOfArguments(nameof(RespCommand.MYCMD));
// 2. Validate other inputs (short-circuit before going to storage)
var key = parseState.GetArgSliceByRef(0);
// e.g., parse and validate optional flags, numeric arguments, etc.
if (!parseState.TryGetInt(1, out var _))
{
WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER);
return true;
}
// 3. Build input/output and call storage API
// Note: To avoid double-parsing a parameter, you can pass a pre-parsed
// value in the input struct's auxiliary arguments (e.g., input.arg1).
var input = new StringInput(RespCommand.MYCMD, ref parseState, startIdx: 1);
var output = GetStringOutput();
var status = storageApi.MyOperation(key, ref input, ref output);
// 4. Write RESP response
if (status == GarnetStatus.OK)
{
ProcessOutput(output);
}
else
{
WriteError(CmdStrings.RESP_ERR_MY_MESSAGE);
}
return true;
}

Key patterns:

  • Arguments: parseState.GetArgSliceByRef(i) returns ref PinnedSpanByte
  • Input/Output: Instantiate StringInput/StringOutput (for string commands), ObjectInput/ObjectOutput (for object commands), or UnifiedInput/UnifiedOutput (for unified commands) before calling the storage API
  • Response (happy path): Use ProcessOutput(output) in the common case — this handles writing the RESP response from the output struct
  • Response (errors/special cases): Use RespServerSession extension methods (e.g., WriteError(...), WriteDirect(...), WriteInt64(...), etc.) — these handle SendAndReset() internally
  • Error strings: Store as u8 literals in CmdStrings (e.g., CmdStrings.RESP_ERR_MY_MESSAGE) rather than inline
  • Always return true — there are no partial executions
Object command RESP handler pattern

Object commands (Hash, List, Set, SortedSet) follow a similar pattern to string commands. The main difference is that the RESP handler uses ObjectInput/ObjectOutput with the appropriate operation enum and must handle WRONGTYPE errors:

File: libs/server/Resp/Objects/[ObjectName]Commands.cs (e.g., SortedSetCommands.cs)

csharp
private unsafe bool SortedSetAdd<TGarnetApi>(ref TGarnetApi storageApi)
where TGarnetApi : IGarnetApi
{
if (parseState.Count < 3)
return AbortWithWrongNumberOfArguments("ZADD");
var key = parseState.GetArgSliceByRef(0);

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files. Certified 30 Sep 2026.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
12,034
Repository forks
709
7-day trend score
47

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill CERTIFIED badge
[![vskill CERTIFIED](https://verified-skill.com/api/v1/skills/microsoft/garnet/add-garnet-command/badge)](https://verified-skill.com/skills/microsoft/garnet/add-garnet-command)

Something wrong with this skill or its page? Tell us.