needle.Field Argument Constraints: Complete Guide to JSON Schema Validation in Needle

needle.Field supports 16 JSON Schema constraints—including numeric bounds, string patterns, array limits, enums, and constants—that are automatically injected into tool schemas via the apply method in needle/agent/tools.py.

The cactus-compute/needle repository provides a lightweight framework for building LLM agents. The needle.Field descriptor enriches Python function parameters with validation metadata, enabling precise argument constraints that downstream consumers and language models can discover through generated JSON Schemas.

What Is needle.Field?

needle.Field is a parameter descriptor used alongside the @tool decorator to attach JSON Schema-compatible validation rules to function arguments. When a function is wrapped with @tool, the framework inspects its signature in needle/agent/tools.py, extracts any Field instances attached to parameters, and invokes field.apply to inject the declared constraints into the generated schema (lines 36–49).

Complete List of Supported Argument Constraints

The Field constructor accepts keyword arguments that map directly to JSON Schema keywords. Here are all supported constraints organized by validation type.

Numeric Range Constraints

Control numeric inputs with inclusive or exclusive boundaries:

  • ge / le: Inclusive lower bound (>=) and upper bound (<=).
  • gt / lt: Exclusive lower bound (>) and upper bound (<).
  • multiple_of: Validates that the value is a multiple of the given number (translates to JSON Schema multipleOf).

String Validation Constraints

Enforce text formatting and length requirements:

  • min_length / max_length: Minimum and maximum character counts (maps to minLength / maxLength).
  • pattern: Regular expression pattern that the string must match.
  • format: JSON Schema format hint such as email, uri, or date-time.

Array Collection Constraints

Validate list structures and contents:

  • min_items / max_items: Minimum and maximum number of elements in an array.
  • unique_items: Boolean flag that, when True, requires all array elements to be distinct (maps to uniqueItems).

Value Enumeration and Constants

Restrict inputs to specific values:

  • enum: List of allowed literal values that the argument must match.
  • const: Single constant value that forces the argument to equal a specific literal.

Documentation and Defaults

Provide metadata and fallback values:

  • description: Human-readable explanation of the parameter's purpose.
  • default (positional): Default value supplied when the argument is omitted from the call.

How Constraints Are Applied to Schemas

During schema generation, the build_schema function iterates over function parameters and invokes field.apply on any attached Field instances. This method copies all non-None constraint values into the JSON Schema dictionary according to the mappings defined in needle/agent/tools.py (lines 19–35).

For example, a Field defined with ge=1 and multiple_of=2 results in a schema containing "minimum": 1 and "multipleOf": 2. This makes the validation rules discoverable by LLM tool callers, API validators, or any consumer processing the generated schema.

Practical Implementation Examples

The following examples demonstrate how to combine multiple constraints on function parameters using needle.Field:

from needle.agent.tools import Field, tool

# Numeric bounds with multiplicity constraint

@tool
def generate_numbers(count: int = Field(ge=1, le=10, multiple_of=2)):
    """Generate an even number of items."""
    return list(range(count))

# String pattern matching with enum restriction

@tool
def set_mode(mode: str = Field(enum=["auto", "manual"], pattern="^(auto|manual)$")):
    """Select operating mode."""
    return f"Mode set to {mode}"

# Array length and uniqueness validation

@tool
def upload_files(files: list = Field(min_items=1, max_items=5, unique_items=True)):
    """Upload a list of file paths."""
    return f"{len(files)} files uploaded"

# Constant value enforcement

@tool
def ping(server: str = Field(const="localhost")):
    """Ping the fixed server."""
    return f"Pinging {server}"

Running build_schema on these functions produces JSON Schema fragments where the constraints appear as standard keywords:

{
  "name": "generate_numbers",
  "parameters": {
    "type": "object",
    "properties": {
      "count": {
        "type": "integer",
        "description": "",
        "minimum": 1,
        "maximum": 10,
        "multipleOf": 2
      }
    },
    "required": ["count"]
  }
}

Summary

  • needle.Field is defined in needle/agent/tools.py and provides 16 JSON Schema-compatible constraint parameters.
  • Numeric constraints include ge, le, gt, lt, and multiple_of for range validation.
  • String constraints include min_length, max_length, pattern, and format for text validation.
  • Array constraints include min_items, max_items, and unique_items for collection validation.
  • Value constraints include enum for allowed lists and const for fixed values.
  • The apply method (referenced in build_schema at lines 36–49) injects these constraints into the final JSON Schema output.

Frequently Asked Questions

How does needle.Field integrate with the @tool decorator?

When you wrap a function with @tool, the decorator inspects the function signature using Python's introspection capabilities. If a parameter has a default value that is a Field instance, the framework extracts the metadata and calls field.apply during build_schema to merge the constraints into the generated JSON Schema. This process is implemented in needle/agent/tools.py between lines 36 and 49.

Can multiple constraints be combined on a single needle.Field?

Yes. You can combine any compatible constraints in a single Field instantiation. For example, Field(ge=0, le=100, multiple_of=5) creates a numeric constraint that accepts only multiples of 5 between 0 and 100 inclusive. The apply method filters out None values and includes all specified constraints in the resulting schema.

What is the difference between the const and enum parameters?

The const parameter restricts the argument to a single, specific value (generating the JSON Schema const keyword), effectively making the parameter read-only or fixed. The enum parameter accepts a list of allowed values (generating the enum keyword), allowing the argument to be any one of several predefined options.

Does needle.Field validate arguments at runtime or only in the schema?

Based on the implementation in needle/agent/tools.py, needle.Field primarily serves as a metadata descriptor that enriches JSON Schema generation. The actual validation of arguments against these constraints typically occurs at the consumer level (such as an LLM client or API validator) that interprets the generated schema, rather than within the Needle framework itself at Python runtime.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →