kuniumi

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

Kuniumi (国産み)

Portable Function Framework for Go

Kuniumi is a framework designed to expose functions written in Go as portable web services through various interfaces (HTTP, CGI, MCP, Docker containers).

Concept: Write Once, Run Anywhere developers focus on implementing business logic (functions), while Kuniumi handles adaptation to execution environments (Adapter) and abstraction of file systems/environment variables (Virtual Environment).

Key Features

  • Multi-Interface: Generate HTTP servers, MCP servers, CGI scripts, and Docker containers from a single Go codebase.
  • Virtual Environment: Secure and portable access to file systems and environment variables via a sandboxed environment.
  • Type Safety: Automatically extracts function metadata using Go's reflection to ensure type-safe interfaces.

Quick Start

Installation
go get github.com/axsh/kuniumi
Basic Implementation (main.go)
package main

import (
    "context"
    "fmt"
    "github.com/axsh/kuniumi"
)

// Function to expose
// context.Context is required to access the VirtualEnvironment
func Add(ctx context.Context, x int, y int) (int, error) {
    // Example: Accessing Virtual Environment
    env := kuniumi.GetVirtualEnv(ctx)
    if env.Getenv("DEBUG") == "true" {
        fmt.Println("Debug mode enabled")
    }

    return x + y, nil
}

func main() {
    app := kuniumi.New(kuniumi.Config{
        Name:    "Calculator",
        Version: "1.0.0",
    })

    // Register function with parameters and return value description
    app.RegisterFunc(Add, "Add two integers",
        kuniumi.WithParams(
            kuniumi.Param("x", "First integer to add"),
            kuniumi.Param("y", "Second integer to add"),
        ),
        kuniumi.WithReturns("Sum of x and y"),
    )

    if err := app.Run(); err != nil {
        panic(err)
    }
}
Build and Run
# Build the application
go build -o calculator main.go

# Run as HTTP Server
./calculator serve --port 8080

# Run as MCP Server (Stdio)
./calculator mcp

# Run as CGI
export PATH_INFO="/Add"
echo '{"x": 10, "y": 20}' | ./calculator cgi

# Get OpenAPI spec via CGI
PATH_INFO="/openapi.json" REQUEST_METHOD=GET ./calculator cgi

# Get OpenAPI spec via HTTP
curl http://localhost:8080/openapi.json

Documentation

For more detailed technical information, please refer to the Architecture Overview.

License

See LICENSE file.

Documentation

Overview

Package kuniumi provides a toolkit for building portable functions that can run as MCP servers, Web APIs, CLIs, and CGI scripts. The core philosophy of Kuniumi is "Write once, run anywhere". By defining a Go function once, you can expose it through multiple interfaces without changing the core logic.

Key Features

  • **Multi-Protocol Support**: Automatically exposes registered functions as Model Context Protocol (MCP) tools, HTTP endpoints, CLI subcommands, and CGI scripts.
  • **Virtual Environment**: Provides a sandboxed environment (`VirtualEnvironment`) for file system access and environment variable management, ensuring consistent behavior across different deployment modes.
  • **Type-Safe Registration**: Functions can be registered with standard Go types, and Kuniumi handles argument parsing and response formatting.
  • **OpenAPI Generation**: Automatically generates OpenAPI definitions for exposed HTTP endpoints.

Usage

To use Kuniumi, create an instance of `App`, register your functions, and then call `Run()`.

package main

import (
	"context"
	"github.com/yourusername/kuniumi"
)

func Hello(ctx context.Context, name string) (string, error) {
	return "Hello, " + name, nil
}

func main() {
	app := kuniumi.New(kuniumi.Config{
		Name:    "my-app",
		Version: "1.0.0",
	})
	app.RegisterFunc(Hello, "Returns a greeting",
		kuniumi.WithParams(
			kuniumi.Param("name", "Name to greet"),
		),
		kuniumi.WithReturns("Greeting message"),
	)
	app.Run()
}

Running the application:

$ my-app serve --port 8080   # Start Web Server
$ my-app mcp                 # Run as MCP Server
$ my-app cgi                 # Run as CGI Script

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CallFunction

func CallFunction(ctx context.Context, meta *FunctionMetadata, args map[string]interface{}) ([]interface{}, error)

CallFunction invokes the function with a map of arguments.

func GenerateJSONSchema

func GenerateJSONSchema(meta *FunctionMetadata) map[string]interface{}

GenerateJSONSchema generates a JSON Schema for the function arguments.

func WithVirtualEnv

func WithVirtualEnv(ctx context.Context, v *VirtualEnvironment) context.Context

WithVirtualEnv adds the VirtualEnvironment to the context.

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is the main application structure for Kuniumi. It manages the lifecycle of the application, including configuration, function registration, command-line argument parsing, and environment management.

App embeds a VirtualEnvironment to provide a consistent runtime across different execution modes (CLI, Server, etc.).

func New

func New(cfg Config, opts ...Option) *App

New creates a new Kuniumi application with the given configuration and options.

Arguments:

  • cfg: The initial configuration for the app (Name, Version).
  • opts: A variadic list of Option functions to further customize the app.

Returns a pointer to the initialized App.

func (*App) ContextWithEnv

func (a *App) ContextWithEnv(ctx context.Context) context.Context

ContextWithEnv returns a new context with the application's VirtualEnvironment attached. This context should be passed to handler functions so they can access the environment via `kuniumi.GetVirtualEnv(ctx)`.

func (*App) RegisterFunc

func (a *App) RegisterFunc(fn interface{}, desc string, opts ...FuncOption)

RegisterFunc registers a Go function to the application, exposing it as a tool/command.

Arguments:

  • fn: The function to register. It supports various signatures, but generally should accept `context.Context` as the first argument and return `(any, error)` or similar.
  • desc: A human-readable description of what the function does.
  • opts: Optional functional options to customize metadata (e.g., argument names).

Example:

app.RegisterFunc(MyFunc, "Does something useful", kuniumi.WithArgs("arg1", "arg2"))

Panics if `fn` is not a function or if analysis fails.

func (*App) Run

func (a *App) Run() error

Run executes the application. This generic entry point automatically handles CLI argument parsing and dispatches to the appropriate subcommand or mode.

Capabilities:

  • **serve**: Starts a clear Web API server.
  • **mcp**: Runs as a Model Context Protocol server (stdio).
  • **cgi**: Executes a single function in CGI mode (useful for serverless/hooks).
  • **containerize**: (Experimental) Helps package the app.

It also parses global flags like `--env` and `--mount` to initialize the Virtual Environment.

type ArgMetadata

type ArgMetadata struct {
	Name        string
	Description string
	Type        reflect.Type
}

type ArgNamesOption

type ArgNamesOption struct {
	Names []string
}

ArgNamesOption allows specifying argument names for a function. This is useful when reflection cannot deduce meaningful parameter names.

type Config

type Config struct {
	// Name is the name of the application.
	Name string
	// Version is the version of the application.
	Version string
}

Config holds the application configuration. It defines the metadata for the application, such as its name and version, which are used in CLI help messages and Open API specifications.

type FileInfo

type FileInfo struct {
	Name  string
	Size  int64
	IsDir bool
}

FileInfo is a simplified file info.

type FuncOption

type FuncOption func(*RegisteredFunc)

FuncOption is a functional option for configuring a registered function. It is used with App.RegisterFunc to customize metadata such as argument names.

func WithArgs

func WithArgs(names ...string) FuncOption

WithArgs returns a FuncOption that specifies custom names for function arguments.

Example:

app.RegisterFunc(MyFunc, "Desc", kuniumi.WithArgs("param1", "param2"))

func WithParams

func WithParams(params ...ParamDef) FuncOption

WithParams returns a FuncOption that associates descriptions with function parameters.

func WithReturns

func WithReturns(desc string) FuncOption

WithReturns returns a FuncOption that specifies the description for the function return value.

type FunctionMetadata

type FunctionMetadata struct {
	Name        string
	Description string
	Args        []ArgMetadata
	Returns     []ReturnMetadata
	FnValue     reflect.Value
}

FunctionMetadata holds information about a registered function.

func AnalyzeFunction

func AnalyzeFunction(fn interface{}, name, desc string) (*FunctionMetadata, error)

AnalyzeFunction inspects a function and returns its metadata.

type Option

type Option func(*App)

Option is a functional option for configuring the App during initialization. It is used with the New function to customize the App instance.

func WithArgNames

func WithArgNames(names ...string) Option

WithArgNames returns an Option that configures argument names. Note: This Option type is for App configuration, but usage here seems to imply function configuration. Use WithArgs for function registration options.

func WithName

func WithName(name string) Option

WithName sets the application name.

type ParamDef

type ParamDef struct {
	Name string
	Desc string
}

ParamDef defines a parameter with its name and description.

func Param

func Param(name, desc string) ParamDef

Param creates a new ParamDef.

type RegisteredFunc

type RegisteredFunc struct {
	Name        string
	Description string
	Meta        *FunctionMetadata
	// contains filtered or unexported fields
}

RegisteredFunc holds metadata about a registered function. It includes the function's name, description, and reflection metadata used for runtime invocation and schema generation.

type ReturnMetadata

type ReturnMetadata struct {
	Description string
	Type        reflect.Type
}

type VirtualEnvironment

type VirtualEnvironment struct {
	// contains filtered or unexported fields
}

VirtualEnvironment provides a sandboxed environment for functions. It abstracts file system operations and environment variable access, allowing functions to run consistently across different environments (local CLI, MCP, Container).

It supports:

  • **Environment Variables**: Managed set of environment variables separate from the host process.
  • **File System Mounting**: Explicitly mounted directories map host paths to virtual paths.
  • **Path Resolution**: Securely resolves virtual paths to host paths, preventing access outside mounted areas.

func GetVirtualEnv

func GetVirtualEnv(ctx context.Context) *VirtualEnvironment

GetVirtualEnv retrieves the VirtualEnvironment from the context. If not found, it returns a safe, empty environment.

func NewVirtualEnvironment

func NewVirtualEnvironment(envVars map[string]string, mounts map[string]string) *VirtualEnvironment

NewVirtualEnvironment creates a new environment.

func (*VirtualEnvironment) ChangeCurrentDirectory

func (v *VirtualEnvironment) ChangeCurrentDirectory(path string) error

ChangeCurrentDirectory changes the current working directory of the virtual environment. The new path must be a valid, existing directory within the mounted filesystems.

Arguments:

  • path: The target virtual path.

Returns an error if the path does not exist, is not a directory, or cannot be resolved.

func (*VirtualEnvironment) Chmod

func (v *VirtualEnvironment) Chmod(path string, mode os.FileMode) error

Chmod changes the permissions of the file at the specified virtual path.

Arguments:

  • path: The virtual path of the file.
  • mode: The new file mode (permissions).

func (*VirtualEnvironment) CopyFile

func (v *VirtualEnvironment) CopyFile(src, dst string) error

CopyFile copies a file from a source virtual path to a destination virtual path. It reads the entire source file and writes it to the destination.

Arguments:

  • src: The source virtual path.
  • dst: The destination virtual path.

Returns an error if either path cannot be resolved or IO operations fail.

func (*VirtualEnvironment) FindFile

func (v *VirtualEnvironment) FindFile(root string, pattern string, recursive bool) ([]string, error)

FindFile searches for files matching a pattern within a virtual directory.

Arguments:

  • root: The virtual root directory to start the search from.
  • pattern: A shell pattern to match filenames (e.g. "*.go").
  • recursive: If true, searches subdirectories recursively.

Returns a list of matching virtual paths.

func (*VirtualEnvironment) GetCurrentDirectory

func (v *VirtualEnvironment) GetCurrentDirectory() string

GetCurrentDirectory returns the current working directory of the virtual environment. The returned path is always a virtual path (e.g. "/src").

func (*VirtualEnvironment) Getenv

func (v *VirtualEnvironment) Getenv(key string) string

Getenv retrieves the value of the environment variable named by the key. It looks up the variable in the virtual environment's managed set. If the variable is not present, it returns an empty string.

func (*VirtualEnvironment) ListEnv

func (v *VirtualEnvironment) ListEnv() map[string]string

ListEnv returns a copy of all environment variables in the virtual environment. The returned map is a copy, so modifying it does not affect the environment.

func (*VirtualEnvironment) ListFile

func (v *VirtualEnvironment) ListFile(path string) ([]FileInfo, error)

ListFile returns a list of files and directories in the specified virtual directory. It returns a slice of FileInfo structs containing name, size, and type information.

Arguments:

  • path: The virtual directory structure to list.

Returns an error if the path is invalid or cannot be read.

func (*VirtualEnvironment) ReadFile

func (v *VirtualEnvironment) ReadFile(path string, offset int64, length int64) ([]byte, error)

ReadFile reads data from a file at the specified virtual path. It allows reading a specific chunk using offset and length.

Arguments:

  • path: The virtual path to read from.
  • offset: The byte offset to start reading from.
  • length: The number of bytes to read.

Returns the read data, or an error if the path cannot be resolved or reading fails. If the file is shorter than (offset + length), it returns the available bytes.

func (*VirtualEnvironment) RemoveFile

func (v *VirtualEnvironment) RemoveFile(path string) error

RemoveFile deletes the file at the specified virtual path.

Warnings:

  • This operation is permanent.
  • It operates on the underlying host file system via the mount point.

func (*VirtualEnvironment) RewriteFile

func (v *VirtualEnvironment) RewriteFile(path string, offset int64, data []byte) error

RewriteFile overwrites data in a file at a specific offset. This preserves the rest of the file content.

Arguments:

  • path: The virtual path of the file.
  • offset: The byte offset to start writing at.
  • data: The new content to write.

Returns an error if the file cannot be opened, path is invalid, or write fails.

func (*VirtualEnvironment) WriteFile

func (v *VirtualEnvironment) WriteFile(path string, data []byte) error

WriteFile writes data to a file at the specified virtual path. The file is created if it does not exist, or truncated if it does. The permission is fixed to 0644.

Arguments:

  • path: The virtual path to write to.
  • data: The content to write.

Returns an error if the path cannot be resolved (not mounted) or if the write fails.

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL