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 ¶
- func CallFunction(ctx context.Context, meta *FunctionMetadata, args map[string]interface{}) ([]interface{}, error)
- func GenerateJSONSchema(meta *FunctionMetadata) map[string]interface{}
- func GenerateOutputJSONSchema(meta *FunctionMetadata) map[string]interface{}
- func WithVirtualEnv(ctx context.Context, v *VirtualEnvironment) context.Context
- type App
- type ArgMetadata
- type ArgNamesOption
- type Config
- type FileInfo
- type FuncOption
- type FunctionMetadata
- type Option
- type ParamDef
- type RegisteredFunc
- type ReturnMetadata
- type VirtualEnvironment
- func (v *VirtualEnvironment) AppendFile(path string, data []byte) error
- func (v *VirtualEnvironment) ChangeCurrentDirectory(path string) error
- func (v *VirtualEnvironment) Chmod(path string, mode os.FileMode) error
- func (v *VirtualEnvironment) CopyFile(src, dst string) error
- func (v *VirtualEnvironment) CreateTemp(dir, pattern string) (string, error)
- func (v *VirtualEnvironment) Exists(path string) (bool, error)
- func (v *VirtualEnvironment) FindFile(root string, pattern string, recursive bool) ([]string, error)
- func (v *VirtualEnvironment) GetCurrentDirectory() string
- func (v *VirtualEnvironment) Getenv(key string) string
- func (v *VirtualEnvironment) ListEnv() map[string]string
- func (v *VirtualEnvironment) ListFile(path string) ([]FileInfo, error)
- func (v *VirtualEnvironment) MkdirAll(path string, perm os.FileMode) error
- func (v *VirtualEnvironment) MkdirTemp(dir, pattern string) (string, error)
- func (v *VirtualEnvironment) ReadFile(path string, offset int64, length int64) ([]byte, error)
- func (v *VirtualEnvironment) RemoveAll(path string) error
- func (v *VirtualEnvironment) RemoveFile(path string) error
- func (v *VirtualEnvironment) Rename(oldPath, newPath string) error
- func (v *VirtualEnvironment) ResolvePath(virtualPath string) (string, error)
- func (v *VirtualEnvironment) RewriteFile(path string, offset int64, data []byte) error
- func (v *VirtualEnvironment) Stat(path string) (os.FileInfo, error)
- func (v *VirtualEnvironment) WriteFile(path string, data []byte) error
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 GenerateOutputJSONSchema ¶ added in v0.1.3
func GenerateOutputJSONSchema(meta *FunctionMetadata) map[string]interface{}
GenerateOutputJSONSchema generates a JSON Schema for the function return values. The schema matches the response format used by the HTTP adapter:
- Single return: {"type": "object", "properties": {"result": <schema>}}
- Multiple returns: {"type": "object", "properties": {"result0": <schema>, "result1": <schema>, ...}}
- No returns (error only): nil
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 ¶
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 ¶
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 ¶
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 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 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 ¶
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.
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.
func (*RegisteredFunc) OperationID ¶ added in v0.1.4
func (rf *RegisteredFunc) OperationID() string
OperationID returns the canonical identifier for this function, used as both the OpenAPI operationId and MCP tool name. Format: "functions.{Name}" (e.g., "functions.Add").
type ReturnMetadata ¶
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) AppendFile ¶ added in v0.1.6
func (v *VirtualEnvironment) AppendFile(path string, data []byte) error
AppendFile appends data to the file at the specified virtual path. If the file does not exist, it is created with permission 0644. If the file exists, data is appended to the end.
Arguments:
- path: The virtual path of the file.
- data: The content to append.
Returns an error if the path cannot be resolved (not mounted) or if the write operation fails.
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) CreateTemp ¶ added in v0.1.6
func (v *VirtualEnvironment) CreateTemp(dir, pattern string) (string, error)
CreateTemp creates a new temporary file in the virtual directory dir with a name that matches the pattern. It is similar to os.CreateTemp but returns a virtual path instead of an *os.File handle.
The pattern follows the same rules as os.CreateTemp: if it includes a "*", the random string replaces the "*"; otherwise, the random string is appended.
The file is created empty and immediately closed. Use WriteFile or AppendFile to write content to it.
Arguments:
- dir: The virtual directory in which to create the temporary file.
- pattern: The pattern for the temporary file name (e.g. "log-*.txt").
Returns the virtual path of the created temporary file, or an error if the directory cannot be resolved or creation fails.
func (*VirtualEnvironment) Exists ¶ added in v0.1.6
func (v *VirtualEnvironment) Exists(path string) (bool, error)
Exists checks whether a file or directory exists at the specified virtual path.
Arguments:
- path: The virtual path to check.
Returns:
- (true, nil) if the file or directory exists.
- (false, nil) if the path resolves successfully but the file does not exist.
- (false, error) if the path cannot be resolved (e.g. not mounted).
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) MkdirAll ¶ added in v0.1.6
func (v *VirtualEnvironment) MkdirAll(path string, perm os.FileMode) error
MkdirAll creates a directory at the specified virtual path, along with any necessary parent directories. It is equivalent to os.MkdirAll.
If the directory already exists, MkdirAll does nothing and returns nil (idempotent behavior).
Arguments:
- path: The virtual path where the directory should be created.
- perm: The permission bits for newly created directories (e.g. 0755).
Returns an error if the path cannot be resolved (not mounted) or if the directory creation fails on the host filesystem.
func (*VirtualEnvironment) MkdirTemp ¶ added in v0.1.6
func (v *VirtualEnvironment) MkdirTemp(dir, pattern string) (string, error)
MkdirTemp creates a new temporary directory in the virtual directory dir with a name that matches the pattern. It is similar to os.MkdirTemp but operates within the virtual filesystem.
The pattern follows the same rules as os.MkdirTemp: if it includes a "*", the random string replaces the "*"; otherwise, the random string is appended.
Unlike os.MkdirTemp, this method returns a virtual path (not a host path), allowing the caller to use it with other VirtualEnvironment methods.
Arguments:
- dir: The virtual directory in which to create the temporary directory.
- pattern: The pattern for the temporary directory name (e.g. "tmp-*").
Returns the virtual path of the created temporary directory, or an error if the directory cannot be resolved or creation fails.
Notes:
- The caller is responsible for removing the directory when it is no longer needed, using RemoveAll.
func (*VirtualEnvironment) ReadFile ¶
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) RemoveAll ¶ added in v0.1.6
func (v *VirtualEnvironment) RemoveAll(path string) error
RemoveAll removes the file or directory at the specified virtual path, including all children if it is a directory. It is equivalent to os.RemoveAll.
As a safety measure, removing a mount point root directory is prohibited and will return an error. This prevents accidental deletion of entire mounted volumes.
Arguments:
- path: The virtual path to remove.
Warnings:
- This operation is permanent and recursive.
- Mount point roots cannot be removed.
Returns an error if the path cannot be resolved, if the path is a mount point root, or if the removal fails.
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) Rename ¶ added in v0.1.6
func (v *VirtualEnvironment) Rename(oldPath, newPath string) error
Rename renames (moves) a file or directory from oldPath to newPath within the virtual filesystem. It is equivalent to os.Rename.
Both paths must resolve to the same mount point. Cross-mount rename operations are not supported and will return an error.
Arguments:
- oldPath: The current virtual path of the file or directory.
- newPath: The desired new virtual path.
Returns an error if either path cannot be resolved, if the paths belong to different mount points, or if the rename operation fails.
func (*VirtualEnvironment) ResolvePath ¶ added in v0.1.6
func (v *VirtualEnvironment) ResolvePath(virtualPath string) (string, error)
ResolvePath converts a virtual path to a real host path. It ensures the path is within the mounted directories, preventing access outside the sandboxed areas.
This method is exported to allow framework users to perform custom file operations using the resolved host path, while maintaining the security guarantees of the mount-based sandboxing.
Arguments:
- virtualPath: The virtual path to resolve. Can be absolute (starting with "/") or relative to the current working directory.
Returns the resolved host filesystem path, or an error if the path is not within any mounted directory.
Security: This method guarantees that the returned path is always within a mounted directory. Path traversal attacks (e.g. "../../etc/passwd") are prevented by path cleaning before mount resolution.
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) Stat ¶ added in v0.1.6
func (v *VirtualEnvironment) Stat(path string) (os.FileInfo, error)
Stat returns the os.FileInfo for the file or directory at the specified virtual path. It is equivalent to os.Stat.
Arguments:
- path: The virtual path to inspect.
Returns the file information, or an error if the path cannot be resolved (not mounted) or if the file does not exist.
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.
Notes:
- The parent directory must already exist. If it does not, use MkdirAll to create it before calling WriteFile.