Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 51 additions & 8 deletions examples/grpc_gnmi_client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,43 @@ import (
"github.com/universal-tool-calling-protocol/go-utcp/src/repository"

"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

type UnifiedServer struct {
grpcpb.UnimplementedUTCPServiceServer
gnmi.UnimplementedGNMIServer
}

const (
user = "alice"
pass = "secret"
)

func checkCreds(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return fmt.Errorf("missing metadata")
}
u := md.Get("username")
p := md.Get("password")
if len(u) == 0 || len(p) == 0 || u[0] != user || p[0] != pass {
return fmt.Errorf("unauthorized")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning a generic fmt.Errorf here causes gRPC to translate the error to status code "Unknown", so the client cannot properly detect an authentication failure. Use status.Error(codes.Unauthenticated, …) instead to return the correct gRPC status code.

Prompt for AI agents
Address the following comment on examples/grpc_gnmi_client/main.go at line 38:

<comment>Returning a generic fmt.Errorf here causes gRPC to translate the error to status code &quot;Unknown&quot;, so the client cannot properly detect an authentication failure. Use status.Error(codes.Unauthenticated, …) instead to return the correct gRPC status code.</comment>

<file context>
@@ -14,18 +14,43 @@ import (
 	&quot;github.com/universal-tool-calling-protocol/go-utcp/src/repository&quot;
 
 	&quot;google.golang.org/grpc&quot;
+	&quot;google.golang.org/grpc/metadata&quot;
 )
 
 type UnifiedServer struct {
 	grpcpb.UnimplementedUTCPServiceServer
 	gnmi.UnimplementedGNMIServer
</file context>

}
return nil
}

func (s *UnifiedServer) Capabilities(ctx context.Context, req *gnmi.CapabilityRequest) (*gnmi.CapabilityResponse, error) {
if err := checkCreds(ctx); err != nil {
return nil, err
}
return &gnmi.CapabilityResponse{}, nil
}

func (s *UnifiedServer) GetManual(ctx context.Context, e *grpcpb.Empty) (*grpcpb.Manual, error) {
if err := checkCreds(ctx); err != nil {
return nil, err
}
return &grpcpb.Manual{
Version: "1.2",
Tools: []*grpcpb.Tool{
Expand All @@ -35,6 +60,9 @@ func (s *UnifiedServer) GetManual(ctx context.Context, e *grpcpb.Empty) (*grpcpb
}

func (s *UnifiedServer) CallTool(ctx context.Context, req *grpcpb.ToolCallRequest) (*grpcpb.ToolCallResponse, error) {
if err := checkCreds(ctx); err != nil {
return nil, err
}
// Simple implementation - could be expanded based on tool name
return &grpcpb.ToolCallResponse{
ResultJson: `{"status": "not implemented for non-streaming"}`,
Expand All @@ -44,6 +72,10 @@ func (s *UnifiedServer) CallTool(ctx context.Context, req *grpcpb.ToolCallReques
func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcpb.UTCPService_CallToolStreamServer) error {
ctx := stream.Context()

if err := checkCreds(ctx); err != nil {
return err
}

if req.Tool == "gnmi_subscribe" {
// Parse args from JSON
var args map[string]interface{}
Expand All @@ -65,10 +97,12 @@ func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcp

// Create a mock update response
update := map[string]interface{}{
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"sub_mode": args["sub_mode"],
"sample_interval_ns": args["sample_interval_ns"],
}

updateJson, err := json.Marshal(update)
Expand Down Expand Up @@ -99,6 +133,10 @@ func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcp
func (s *UnifiedServer) Subscribe(stream gnmi.GNMI_SubscribeServer) error {
ctx := stream.Context()

if err := checkCreds(ctx); err != nil {
return err
}

// Single-sender to keep gRPC Send safe.
out := make(chan *gnmi.SubscribeResponse, 32)
defer close(out)
Expand All @@ -121,8 +159,11 @@ func (s *UnifiedServer) Subscribe(stream gnmi.GNMI_SubscribeServer) error {
Update: &gnmi.Notification{
Timestamp: time.Now().UnixNano(),
Update: []*gnmi.Update{{
Path: &gnmi.Path{Element: []string{"interfaces", "interface", "eth0"}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: state}},
Path: &gnmi.Path{Elem: []*gnmi.PathElem{
{Name: "interfaces"},
{Name: "interface", Key: map[string]string{"name": "eth0"}},
}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: state}},
}},
},
},
Expand Down Expand Up @@ -229,8 +270,10 @@ func main() {
}

stream, err := client.CallToolStream(ctx, "gnmi.gnmi_subscribe", map[string]any{
"path": "/interfaces/interface/eth0",
"mode": "STREAM",
"path": "/interfaces/interface[name=eth0]",
"mode": "STREAM",
"sub_mode": "SAMPLE",
"sample_interval_ns": 500000000,
})
if err != nil {
log.Fatalf("call stream: %v", err)
Expand Down
7 changes: 6 additions & 1 deletion examples/grpc_gnmi_client/provider.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
"host": "127.0.0.1",
"port": 9339,
"service_name": "gnmi.gNMI",
"method_name": "Subscribe"
"method_name": "Subscribe",
"auth": {
"auth_type": "basic",
"username": "alice",
"password": "secret"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hard-coded plaintext credential exposes a real-looking password in the repository and risks accidental leakage; replace with a placeholder or environment substitution.

Prompt for AI agents
Address the following comment on examples/grpc_gnmi_client/provider.json at line 13:

<comment>Hard-coded plaintext credential exposes a real-looking password in the repository and risks accidental leakage; replace with a placeholder or environment substitution.</comment>

<file context>
@@ -6,7 +6,12 @@
       &quot;host&quot;: &quot;127.0.0.1&quot;,
       &quot;port&quot;: 9339,
       &quot;service_name&quot;: &quot;gnmi.gNMI&quot;,
-      &quot;method_name&quot;: &quot;Subscribe&quot;
+      &quot;method_name&quot;: &quot;Subscribe&quot;,
+      &quot;auth&quot;: {
+        &quot;auth_type&quot;: &quot;basic&quot;,
+        &quot;username&quot;: &quot;alice&quot;,
+        &quot;password&quot;: &quot;secret&quot;
</file context>
Suggested change
"password": "secret"
"password": "${GNMI_PASSWORD}"

}
}
]
}
60 changes: 52 additions & 8 deletions examples/grpc_gnmi_transport/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,42 @@ import (
"time"

gnmi "github.com/openconfig/gnmi/proto/gnmi"
auth "github.com/universal-tool-calling-protocol/go-utcp/src/auth"
"github.com/universal-tool-calling-protocol/go-utcp/src/grpcpb"
. "github.com/universal-tool-calling-protocol/go-utcp/src/providers/base"
providers "github.com/universal-tool-calling-protocol/go-utcp/src/providers/grpc"
transports "github.com/universal-tool-calling-protocol/go-utcp/src/transports/grpc"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

type UnifiedServer struct {
gnmi.UnimplementedGNMIServer
grpcpb.UnimplementedUTCPServiceServer
}

const (
user = "alice"
pass = "secret"
)

func checkCreds(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return fmt.Errorf("missing metadata")
}
u := md.Get("username")
p := md.Get("password")
if len(u) == 0 || len(p) == 0 || u[0] != user || p[0] != pass {
return fmt.Errorf("unauthorized")
}
return nil
}

func (s *UnifiedServer) CallTool(ctx context.Context, req *grpcpb.ToolCallRequest) (*grpcpb.ToolCallResponse, error) {
if err := checkCreds(ctx); err != nil {
return nil, err
}
// Simple implementation - could be expanded based on tool name
return &grpcpb.ToolCallResponse{
ResultJson: `{"status": "not implemented for non-streaming"}`,
Expand All @@ -31,6 +54,10 @@ func (s *UnifiedServer) CallTool(ctx context.Context, req *grpcpb.ToolCallReques
func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcpb.UTCPService_CallToolStreamServer) error {
ctx := stream.Context()

if err := checkCreds(ctx); err != nil {
return err
}

if req.Tool == "gnmi_subscribe" {
// Parse args from JSON
var args map[string]interface{}
Expand All @@ -52,10 +79,12 @@ func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcp

// Create a mock update response
update := map[string]interface{}{
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"sub_mode": args["sub_mode"],
"sample_interval_ns": args["sample_interval_ns"],
}

updateJson, err := json.Marshal(update)
Expand Down Expand Up @@ -84,10 +113,16 @@ func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcp
}

func (s *UnifiedServer) Capabilities(ctx context.Context, req *gnmi.CapabilityRequest) (*gnmi.CapabilityResponse, error) {
if err := checkCreds(ctx); err != nil {
return nil, err
}
return &gnmi.CapabilityResponse{}, nil
}

func (s *UnifiedServer) GetManual(ctx context.Context, e *grpcpb.Empty) (*grpcpb.Manual, error) {
if err := checkCreds(ctx); err != nil {
return nil, err
}
return &grpcpb.Manual{
Version: "1.2",
Tools: []*grpcpb.Tool{
Expand All @@ -97,14 +132,22 @@ func (s *UnifiedServer) GetManual(ctx context.Context, e *grpcpb.Empty) (*grpcpb
}

func (s *UnifiedServer) Subscribe(stream gnmi.GNMI_SubscribeServer) error {
ctx := stream.Context()

if err := checkCreds(ctx); err != nil {
return err
}
if _, err := stream.Recv(); err != nil {
return err
}
resp := &gnmi.SubscribeResponse{
Response: &gnmi.SubscribeResponse_Update{
Update: &gnmi.Notification{Update: []*gnmi.Update{{
Path: &gnmi.Path{Element: []string{"interfaces", "interface", "eth0"}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: "UP"}},
Path: &gnmi.Path{Elem: []*gnmi.PathElem{
{Name: "interfaces"},
{Name: "interface", Key: map[string]string{"name": "eth0"}},
}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: "UP"}},
}}},
},
}
Expand All @@ -130,14 +173,15 @@ func main() {

logger := func(format string, args ...interface{}) { log.Printf(format, args...) }
tr := transports.NewGRPCClientTransport(logger)
prov := &providers.GRPCProvider{BaseProvider: BaseProvider{Name: "g", ProviderType: ProviderGRPC}, Host: "127.0.0.1", Port: 9339, ServiceName: "gnmi.gNMI", MethodName: "Subscribe"}
var a auth.Auth = auth.NewBasicAuth(user, pass)
prov := &providers.GRPCProvider{BaseProvider: BaseProvider{Name: "g", ProviderType: ProviderGRPC}, Host: "127.0.0.1", Port: 9339, ServiceName: "gnmi.gNMI", MethodName: "Subscribe", Auth: &a}

ctx := context.Background()
if _, err := tr.RegisterToolProvider(ctx, prov); err != nil {
log.Fatalf("register: %v", err)
}

stream, err := tr.CallToolStream(ctx, "gnmi_subscribe", map[string]any{"path": "/interfaces/interface/eth0", "mode": "STREAM"}, prov)
stream, err := tr.CallToolStream(ctx, "gnmi_subscribe", map[string]any{"path": "/interfaces/interface[name=eth0]", "mode": "STREAM", "sub_mode": "SAMPLE", "sample_interval_ns": 500000000}, prov)
if err != nil {
log.Fatalf("call stream: %v", err)
}
Expand Down
Loading
Loading